多维数组判断是否使用基于标志的值
multidimensional array tell if a use a value based on flag
Array (
[0] => Array ( [address] => New York [address_flag] => 0 )
[1] => Array ( [address] => London [address_flag] => 1)
假设我上面有这个数组,address 1
将永远存在,而 address 2
可以为 null 如何获取 address 2
的值(如果可用);如何获取我告诉 address 2
是否为空?
我正在这样获取它们的价值
foreach (address() as $value) {
echo $value['address']
}
UPDATE
只有当带有标志 1 的地址不可用时,我才想使用带有标志 0 的地址..如何解决这个问题?任何想法表示赞赏
foreach (address() as $value) {
echo isset($value['address']) ? $value['address'] : "";
echo isset($value['address_flag']) ? $value['address_flag'] : "";
}
<?php
function address(){
$a = array(array ( "address" => "New York", "address_flag" => 0 ),
array ( "address" => "London", "address_flag" => 1 ),
array ( "address" => "Amsterdam","address_flag" => 1),
array ( "address" => null, "address_flag" => null));
return $a;
}
$address = '';
$grouped_by_zero = array();
$grouped_by_one = array();
$array = address();
for ($i=0, $max = count($array); $i < $max; $i++ ){
foreach($array[$i] as $key => $value) {
if ($key == "address") {
$address = $value;
}
if ($key == "address_flag"){
if ( $value === 0 ){
array_push($grouped_by_zero,$address);
} else if ($value === 1) {
array_push($grouped_by_one,$address);
}
}// end outer if
}// end foreach
}// end for
foreach($grouped_by_zero as $item){
echo $item . "\n";
}
echo "\n";
foreach($grouped_by_one as $item){
echo $item . "\n";
}
//output:
New York
London
Amsterdam
通过使用恒等运算符===
,排除空值;只接受等于 0 或 1 的值。
Array (
[0] => Array ( [address] => New York [address_flag] => 0 )
[1] => Array ( [address] => London [address_flag] => 1)
假设我上面有这个数组,address 1
将永远存在,而 address 2
可以为 null 如何获取 address 2
的值(如果可用);如何获取我告诉 address 2
是否为空?
我正在这样获取它们的价值
foreach (address() as $value) {
echo $value['address']
}
UPDATE
只有当带有标志 1 的地址不可用时,我才想使用带有标志 0 的地址..如何解决这个问题?任何想法表示赞赏
foreach (address() as $value) {
echo isset($value['address']) ? $value['address'] : "";
echo isset($value['address_flag']) ? $value['address_flag'] : "";
}
<?php
function address(){
$a = array(array ( "address" => "New York", "address_flag" => 0 ),
array ( "address" => "London", "address_flag" => 1 ),
array ( "address" => "Amsterdam","address_flag" => 1),
array ( "address" => null, "address_flag" => null));
return $a;
}
$address = '';
$grouped_by_zero = array();
$grouped_by_one = array();
$array = address();
for ($i=0, $max = count($array); $i < $max; $i++ ){
foreach($array[$i] as $key => $value) {
if ($key == "address") {
$address = $value;
}
if ($key == "address_flag"){
if ( $value === 0 ){
array_push($grouped_by_zero,$address);
} else if ($value === 1) {
array_push($grouped_by_one,$address);
}
}// end outer if
}// end foreach
}// end for
foreach($grouped_by_zero as $item){
echo $item . "\n";
}
echo "\n";
foreach($grouped_by_one as $item){
echo $item . "\n";
}
//output:
New York
London
Amsterdam
通过使用恒等运算符===
,排除空值;只接受等于 0 或 1 的值。