duanjucong3124 2015-01-13 06:19 采纳率: 100%
浏览 24
已采纳

多维数组告诉是否使用基于flag的值

Array ( 
[0] => Array ( [address] => New York [address_flag] => 0 ) 
[1] => Array ( [address] => London [address_flag] => 1)

Lets say i have this array above, address 1 will always be there while address 2 can be null how can i get the value of address 2 if it is available;how can i tell that address 2 is null or not?

I am getting their value like this

foreach (address() as $value) {

echo $value['address']

}

UPDATE

I want to use the address with flag 0 only if address with flag 1 is not available..how do go about this?any idea is appreciated

  • 写回答

2条回答 默认 最新

  • dongzhonggua4229 2015-01-13 07:11
    关注
    <?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 . "
    ";
    }
    echo "
    ";
    foreach($grouped_by_one as $item){
        echo $item . "
    ";
    }
    //output:
    
    New York
    
    London
    Amsterdam
    

    Live demo: http://3v4l.org/3utBH

    By using the identity operator ===, a null value is excluded; only a value that is identical to a 0 or 1 is accepted.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计