user1032531 user1032531 - 1 year ago 258
PHP Question

Using php's array_search on an array of objects allows me to find the first array key based on an array value.

Can this be accomplished with a single PHP function if the value is nested in an object in the array values, or must it be manually performed as I show below?

Thank you

function getKeyBasedOnName($arr,$name)
foreach($arr as $key=>$o) {
if($o->name==$name) return $key;
return false;
"name": "zero",
"data": [107, 31, 635, 203, 2]
"name": "one",
"data": [133, 156, 947, 408, 6]
{"name": "two",
"data": [1052, 954, 4250, 740, 38]
var_dump(getKeyBasedOnName($arr,'zero')); //Return 0
var_dump(getKeyBasedOnName($arr,'one')); //Return 1
var_dump(getKeyBasedOnName($arr,'two')); //Return 2
var_dump(getKeyBasedOnName($arr,'three')); //Return false

Answer Source

Just for fun, if the array is 0 based and sequential keys:

echo array_search('zero', array_column(json_decode($json, true), 'name'));
  • Extract all the name key values into a single array
  • Search for the name value to return the key

This decodes the JSON into an array. You can decode it to an object after if you need that. As of PHP 7 you can use an array of objects:

$arr = json_decode($json);
echo array_search('zero', array_column($arr, 'name'));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download