http://php.net/manual/en/function.array-search.php 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
<?php
function getKeyBasedOnName($arr,$name)
{
foreach($arr as $key=>$o) {
if($o->name==$name) return $key;
}
return false;
}
$json='[
{
"name": "zero",
"data": [107, 31, 635, 203, 2]
},
{
"name": "one",
"data": [133, 156, 947, 408, 6]
},
{"name": "two",
"data": [1052, 954, 4250, 740, 38]
}
]';
$arr=json_decode($json);
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
nameis not set that will throw a notice. Maybe revise your if toif ( property_exists($o, 'name') && $o->name == $name) {...array_search().array_filtercould be used this way? It'd end up being as verbose as what you've done, because to use an "outside value", you have do put it in a class and wrap it in a function. As an aside, after working in Javascript / Angular more recently, and using the lodash library and finding it super useful, I often lament not having better tools like this. Have considered using this library which ports many of those super-useful functions to php.array_usearchfunction that allows you to supply a compare function. Wouldn't be hard to make one yourself.