-1

Ok so I have a JSON string looks like this.

{
    "1": [
        "a",
        "ab",
        "ac"
    ],
    "3": [
        "v",
        "aw",
        "ea"
    ],
    "4": [
        "ffg",
        "sd"
    ]
}

I decoded it with json_decode($string, true); Now, I need to find a way to check, for example, is a exists? If it exists, I want to know the name of its parent value(e.g. 1). The keys and values aren't always the same, they will keep changing. Can anyone provide me an example code on how can I do this? Thanks in advanced ;)

Jeremy
  • 105
  • 1
  • 4
  • 11

1 Answers1

0

That string is gives me back null, if i tried to convert it to JSON, so i've just built an array to you for example. I've just create a function, and loop through on all the key of that. After that, in the sub array, loop through again to check the first occurence of the searched string. If you need all the results, then you can strore the keys in an array, and return with that.

//The string we search
$searchString = "aw";

//The array where we search
$array = array(
    "1" => array("a", "ab", "ac"),
    "3" => array("v", "aw", "ea"),
    "4" => array("ffg", "sd")
);


$result = getArrayIndex($array, $searchString);
if (empty($result)) {
    "I did not find your string: " . $searchString;
} else {
    echo "The index of your main array, where  '" . $searchString . "' found is: " . $result;
}

function getArrayIndex($array, $searchString) {
    if (count($array)) {
        foreach (array_keys($array) as $key) {
            if (is_array($array[$key])) {
                foreach ($array[$key] as $item) {
                    if ($item === $searchString) {
                        return $key;
                    }
                }
            }
        }
    }
    return false;
}
vaso123
  • 12,347
  • 4
  • 34
  • 64