0

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?

Dharman
  • 30,962
  • 25
  • 85
  • 135
AlamHo
  • 193
  • 1
  • 3
  • 12

2 Answers2

0

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.

Enbee
  • 128
  • 9
0

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
}
}
Ranjan
  • 180
  • 2
  • 8