简体   繁体   English

PHP,在foreach语句中从数组获取值

[英]PHP, Get value from array in a foreach statement

I have an array in PHP defined like this: 我在PHP中定义了一个数组,如下所示:

array(4) {
  [2]=>
  array(35) {
    [64055]=>
    int(1)
    [63682]=>
    int(1)
    [63441]=>
    int(1)
    [63180]=>
    int(1)
    [62867]=>
    int(1)
    [62866]=>
    int(1)
    [62801]=>
    int(1)
    [62425]=>
    int(1)
    [61557]=>
    int(1)
    [61432]=>
    int(1)
    [60777]=>
    int(1)
    [60473]=>
    int(1)
    [60181]=>
    int(1)
    [56466]=>
    int(1)
    [54520]=>
    int(1)
    [54368]=>
    int(1)
    [52155]=>
    int(1)
    [52090]=>
    int(1)
    [51399]=>
    int(1)
    [51081]=>
    int(1)
    [48540]=>
    int(1)
    [45649]=>
    int(1)
    [45099]=>
    int(1)
    [43147]=>
    int(1)
    [39122]=>
    int(1)
    [37309]=>
    int(1)
    [29849]=>
    int(1)
    [28732]=>
    int(1)
    [23916]=>
    int(1)
    [23644]=>
    int(1)
    [23351]=>
    int(1)
    [21351]=>
    int(1)
    [16970]=>
    int(1)
    [16781]=>
    int(1)
    [16763]=>
    int(1)
  }
  [6]=>
  array(1) {
    [63854]=>
    int(1)
  }
  [4]=>
  array(7) {
    [62921]=>
    int(1)
    [58863]=>
    int(1)
    [50981]=>
    int(1)
    [49118]=>
    int(1)
    [36078]=>
    int(1)
    [27718]=>
    int(1)
    [21813]=>
    int(1)
  }
  [21]=>
  array(1) {
    [38328]=>
    int(1)
  }
}

How can I loop through this array to get the digits [2], [6], and [4]? 如何遍历此数组以获得数字[2],[6]和[4]? I want to print out those digits. 我想打印出这些数字。 Anyone who can help me with this? 有人可以帮助我吗? I can't figure it out how to do an foreach to do this. 我不知道如何做一个foreach做到这一点。

Since they are the keys of your array elements, array_keys() should do: 由于它们是数组元素的键,因此array_keys()应该这样做:

$keys = array_keys($array);

To print them, comma seperated: 要打印它们,请用逗号分隔:

echo implode(', ', array_keys($array));

Use foreach : 使用foreach

$result = array();
foreach ($array as $key => $value){
    array_push($result, $key)
}
foreach($array as $key=>$val) {
   if($key == 2 || $key == 4 || $key == 6)
      print_r($array[$key]);
}

Hope this helps :D 希望这会有所帮助:D

Georges answer si the best but if you wanted a foreach its 乔治回答si最好,但如果您要进行攻打,

foreach ($array as $key => $value) {
    echo $key;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM