I have the following setup where I'm trying to use an array of array structure. I'm not sure how to get the key value once the value is found in the array of arrays.
$testboat = 'smallest boat';
$allboats = array(40=>array(1=>'big boat',
2=>'bigger boat'
),
30=>array(1=>'little boat',
2=>'tiny boat',
3=>'smallest boat'));
foreach($allboats as $boats){
foreach($boats as $boat){
if($testboat == $boat) {
/*looking to echo the key or value 30; */
}
}
}
Use the $key => $value
syntax of foreach()
. Also, no need to loop through the inner arrays:
foreach($allboats as $key => $boats){
if(in_array($testboat, $boats)) {
echo $key;
break; //if you want to stop after found
}
}
If you want to get the outer key and the inner key:
foreach($allboats as $key => $boats){
if(($inner_key = array_search($testboat, $boats)) !== false) {
echo "$key and $inner_key";
break; //if you want to stop after found
}
}
$testboat = 'smallest boat';
$allboats = array(40=>array(1=>'big boat',
2=>'bigger boat'
),
30=>array(1=>'little boat',
2=>'tiny boat',
3=>'smallest boat'));
foreach($allboats as $id => $boats){
//$id will be 40, then 30
foreach($boats as $id2 => $boat){
//$id2 will be 1,2...
if($testboat == $boat) {
echo $id . '-' . $id2;
/*looking to echo the key or value 30; */
}
}
}
You'd have to do the following:
foreach($allboats as key1 => $boats){
foreach($boats as key2 => $boat){
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.