I\'m trying to search for a value in a multi dimensional array (below is only a part of the big array) and get the key for that value but I can\'t manage it by myself. Here is w
PHP code demo
<?php
$array=Array
(
0=> Array
(
0=> "SMEG - 30",
1=> "ALES",
2=> "-",
3=> "-",
4=> "-",
5=> "ALES",
6=> "44-",
7=> "-",
8=> "FR*S30*E36*1*1",
9=> "FR*S30*E36*1*1",
10=> "US*S30",
11=> "Oui",
12=> "3376",
13=> "Normale",
14=> "-"
),
1=> Array
(
0=> "SMEG - 30",
1=> "ALES",
2=> "-",
3=> "Chemin Des Sports",
4=> "-",
5=> "ALES",
6=> "-",
7=> "-",
8=> "FR*S30*E37*2*1",
9=> "FR*S30*E37*2*1",
10=> "FR*S30",
11=> "Oui",
12=> "33762",
13=> "Normale",
14=> "-",
),
2=> Array
(
0=> "SMEG - 30",
1=> "ALES",
2=> "0",
3=> "Ecole Des Mines",
4=> "-",
5=> "ALES",
6=> "4-",
7=> "-",
8=> "FR*S30*E38*2*1",
9=> "FR*S30*E38*2*1",
10=> "FR*S30",
11=> "Oui",
12=> "3376",
13=> "Normale",
14=> "-",
)
);
$requiredKey=null;
$requiredValue=null;
finder($array,"FR*S30*E37*2*1");
function finder($array,$search)
{
global $requiredKey,$requiredValue;
foreach($array as $key => $value)
{
if(in_array($search, $value))
{
$requiredKey=$key;
$requiredValue=$search;
break;
}
}
}
echo $requiredKey;
echo $requiredValue;
Try this function for recursive searching:
function array_search_recursive($needle, array $haystack)
{
foreach ($haystack as $key => $value) {
$current_key = $key;
if ($needle === $value or (is_array($value) && array_search_recursive($needle, $value) !== false)) {
return $current_key;
}
}
return false;
}
$key = array_search_recursive("FR*S30*E37*2*1", $data);
If you don't need to key, you could use array_filter
$result = array_filter($data, function($item) use ($search) {
return $item[8] == $search;
})[0];
If you need the key, you could modify it like this
$key = false;
$result = array_filter($data, function($item, $k) use ($search, &$key) {
if ($item[8] == $search) {
$key = $k;
return true;
}
return false;
}, ARRAY_FILTER_USE_BOTH)[0];
To handle cases, where no result is found, you have to skip the [0]
party and test if count($result) != 0