if an array default is true, how to display his content?

感情迁移 提交于 2019-12-12 03:34:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!