There is such a JSON file:

{ "terminals": [ { "token": "hile_abcd1234", "name": "Hile Group Authorized Agent", "scopes": [ "r" ] }, { "token": "hile_absd1234", "name": "Hile Group Authorized Agent 2", "scopes": [ "w" ] } ] } 

How to find the token hile_absd1234 and return the array in which it is located?

    3 answers 3

     $arr = json_decode($string, true); $res = array_filter($arr['terminals'], function($x) { return $x['token'] == 'hile_absd1234'; }); 

    demo

    • Another question is how do i get an array of scopes . This is what I get your code: Array ( [1] => Array ( [token] => hile_absd1234 [name] => Hile Group Authorized Agent 2 [scopes] => Array ( [0] => w ) ) ) - LazyTechwork
    • maybe it makes sense to add array_pop - teran
    • @teran Why? - LazyTechwork
    • @ splash58 is not true, $res[1]['scopes'] , and therefore wrote that pop does not hurt. - teran
    • @Teran yes, I didn’t see it for sure. Perhaps even a cycle is necessary if there is no certainty that the result is only one element - splash58

    Yes, like nothing complicated?

     $json = '{"terminals":[{"token":"hile_abcd1234","name":"Hile Group Authorized Agent","scopes":["r"]},{"token":"hile_absd1234","name":"Hile Group Authorized Agent 2","scopes":["w"]}]}'; $data = json_decode($json, true); $result = null; $needle = "hile_absd1234"; foreach($data['terminals'] as $t){ if($t['token'] === $needle){ $result = $t; break; } } print_r($result); 

    as already described by @ splash58, you can use array_filter , but here you will end up with an array, inside which is the desired result. An alternative could be array_reduce

     $result = array_reduce($data['terminals'], function($carry, $item) use ($needle){ if($item['token'] === $needle){ $carry = $item; } return $carry; }); print_r($result); 

    it will immediately return the desired array.

    the disadvantage of both functions of arrays is that they will scan the entire array completely, while in the loop we can make a break after finding the element.

    • Warning: Invalid argument supplied for foreach () returns , when I check, the contents of the file outputs, and the conversion of json to the object displays the empty array - LazyTechwork
    • @IvanSteklow how, from where and in what form do you read the file? - teran

    Another option to the collection:

     $need = 'hile_absd1234'; $result = []; $array = json_decode($string, true); foreach ($array as $arr) { foreach ($arr as $k => $v) { if ($v['token'] == $need) { $result[] = $arr[$k]; } } } echo '<pre>', print_r($result, true), '</pre>';