JavaScript
x
Array ( [type] => 101 [width] => 540 [height] => 960 [url] => https://a.com)
Array ( [type] => 102 [width] => 340 [height] => 604 [url] => https://b.com)
Array ( [type] => 103 [width] => 240 [height] => 430 [url] => https://c.com)
Array ( [type] => 104 [width] => 240 [height] => 420 [url] => https://d.com)
How to get data from this array of only [type] => 102
?
Advertisement
Answer
Simple and easy-to-understand solution could be as next.
The main idea – find index of required type
and then retrieve data from this index.
Once you’ve find your type
you will catch the index and break the loop:
JavaScript
$indd = ''; // possible array index with required type value
$type = 102; // type value
foreach($ar as $ind=>$arr){
if ($arr['type'] == $type) {
$indd = $ind;
break;
}
}
With catched index you can easy get rest of data:
JavaScript
if($indd){
echo $ar[$indd]['width'].PHP_EOL;
echo $ar[$indd]['height'].PHP_EOL;
echo $ar[$indd]['url'].PHP_EOL.PHP_EOL;
}
Outputs:
JavaScript
340
604
https://b.com
All in one function could be present like:
JavaScript
function arrayByType($arra, $type){
$indd = '';
foreach($arra as $ind=>$arr){
if ($arr['type'] == $type) {
$indd = $ind;
break;
}
}
if($indd){
return $arra[$indd];
}
}
Outputs:
JavaScript
Array
(
[type] => 102
[width] => 340
[height] => 604
[url] => https://b.com
)
NOTE: This solution works properly in case of unique type
value. Multiple appearances don’t supports.