问题
if I have an array with the following structure:
$currencies = Array (7)
0 => Array (3)
id => "11"
code => "CHF"
default => "0"
1 => Array (3)
id => "13"
code => "USD"
default => "0"
2 => Array (3)
id => "12"
code => "EUR"
default => "1"
I would like to retrieve the 'code' when default is equal to '1', something like:
if($currencies.default == 1 ){
$currency_code = EUR
}
That was just a rough example of my intention, I have no idea how to do it. Can anyone help me?
回答1:
This should work for you:
First you go through each element with array_filter() and filter all those subArrays out, which don't have default => 1.
After this just simply grab the column code out of the filtered array from before with array_column(), e.g.
<?php
$result = array_column(array_filter($currencies, function($v){
return $v["default"] == 1;
}), "code");
print_r($result);
?>
output:
Array
(
[0] => EUR
)
回答2:
Try using array_filter(). Example:
$result = array_filter($currencies, function($v){return $v['default'] == 1 ? $v['code'] : false;});
print '<pre>';
print_r($result);
print '</pre>';
来源:https://stackoverflow.com/questions/31658445/if-an-array-default-is-true-how-to-display-his-content