douduocuima61392 2010-01-13 05:56
浏览 54

PHP:获取当前数组键?

$array = ( 
    array('1231415'=>array('foo'=>'bar', 'test'=> 1)),
    array('32434'=>array('foo'=>'bar', 'test'=> '0')),
    array('123244'=>array('foo'=>'bar', 'test'=> 0)),
    array('193928'=>array('foo'=>'bar', 'test'=> 1))
);

I have an array that has (many) random keys, the ID number. I need to test each array within if 'test' = 1, and so I made a foreach loop.

foreach ($array as $sub) {
  if ($sub['test'] == '1' ) {
     echo 'User: ' . $sub . ' has test = 1';
  }
}

This works, but it returns 'User: Array has test = 1'

How on earth to I get which ID number, (that random number) has test=1 in it?

I tried doing $array as $sub=>$value, but for some reason it just makes the foreach not work. Thank you!

  • 写回答

2条回答 默认 最新

  • doutangtan6386 2010-01-13 05:58
    关注

    Use this foreach syntax instead:

    foreach ($array as $key => $sub) {
      if ($sub['test'] == '1' ) {
        echo 'User: ' . $key . ' has test = 1';
      }
    }
    

    This assumes that the data is in the form:

    $array = array(
      '1234' => array('test' => 1),
      '5678' => array('test' => 2)
    );
    

    If you need to keep your data as it is now, you'll need to use something more like:

    foreach ($array as $item) {
      list($key, $info) = $item;
      if ($info['test'] == 1) {
        echo 'User: ' . $key . ' has test = 1';
      }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型