Assume I have this array list in php
[
{
"id": "1",
"name": "test1",
},
{
"id": "2",
"name": "test2",
},
]
How can I easily return the id that have name=test1?
Try using array_search()
. First, get the place of the id, name pair and get the content of the id field next.
//Get the key of the 'id, name' pair
$key = array_search('test2', array_column($input, 'name'));
//Get the id beloning to the name
$id = $input[$key]->id;
A working example here.
I assume you have multilevel array, so you do using foreach function as below.
$x= array(array('id'=>'1','name'=>'test1'),array('id'=>'2','name'=>'test2'));
foreach($x as $value){
if($value['id'] =="1" && $value['name'] == "test1"){
// Do your stuff
}
}