I have an array, what Is like this:
$itemx=
[
'Weapons'=>[
'Sword'=> [
'ID' => '1',
'Name' => 'Lurker',
'Value' => '12',
'Made' => 'Acient'
],
'Shield'=> [
'ID' => '2',
'Name' => 'Obi',
'Value' => '22',
'Made' => 'Acient'
],
'Warhammer'=> [
'ID' => '3',
'Name' => 'Clotch',
'Value' => '124',
'Made' => 'Acient'
]
],
'Drinks'=>[
'Water'=> [
'ID' => '4',
'Name' => 'Clean-water',
'Value' => '1',
'Made' => 'Acient'
],
'Wine'=> [
'ID' => '5',
'Name' => 'Soff',
'Value' => '5',
'Made' => 'Acient'
],
'Vodka'=> [
'ID' => '6',
'Name' => 'Laudur',
'Value' => '7',
'Made' => 'Acient'
]
]
];
I want to find an array from it by Name or ID, so my output should be like this.
*Search by ID=4*
'Water'=> [
'ID' => '4',
'Name' => 'Clean-water',
'Value' => '1',
'Made' => 'Acient'
]
I look at other topics and found that I should use array_search
But It didn't work. I tried like this:
$arra=$itemx["Drinks"];
$key = array_search(4, array_column($arra, 'ID'));
var_dump($arra[$key]);
It also dident work when I tried with Name
as a search key.
How can I get this working?
You can do it like below:-
$search_id = 4;
$final_array = [];
foreach($itemx as $key=>$val){
foreach($val as $k=>$v){
if($v['ID'] == $search_id){
$final_array[$k] = $itemx[$key][$k];
}
}
}
print_r($final_array);