I have a PHP array and I need to find an item based on a key within the tlp_queue_manager_schedulers
object, I tried doing array_search
but this returned false, I also tried combining this method with array_column
:
[
{
"tlp_queue_manager_schedulers":{
"id":"1",
"token":"ABC"
},
"0":{
"num":"1"
}
},
{
"tlp_queue_manager_schedulers":{
"id":"3",
"token":"cron-3"
},
"0":{
"num":"2"
}
},
{
"tlp_queue_manager_schedulers":{
"id":"4",
"token":"CronA75nvAgjsm8b"
},
"0":{
"num":"3"
}
},
{
"tlp_queue_manager_schedulers":{
"id":"2",
"token":"XYZ"
},
"0":{
"num":"4"
}
}
]
For example, I need to return the array item where the id
key within tlp_queue_manager_schedulers
matches 3, this should then return:
{
"tlp_queue_manager_schedulers":{
"id":"3",
"token":"cron-3"
},
"0":{
"num":"2"
}
}
CodePudding user response:
You can try the find() method
var result = array.find(x => x.tlp_queue_manager_schedulers.id === '3');
console.log(result);
https://jsfiddle.net/kenpy/trj543xy/24/
CodePudding user response:
Good ol' foreach
loop. Nothing beats a foreach
loop:
foreach($array as $obj)
{
if($obj->tlp_queue_manager_schedulers->id == "3")
{
return $obj;
}
}