【问题标题】:get the index of the array in php在php中获取数组的索引
【发布时间】:2013-11-20 03:07:33
【问题描述】:

我有一个包含以下内容的数组:

$code_ids
 [138]=>
  string(0) "asdsad"
  [126]=>
  string(0) ""
  [163]=>
  string(0) "asdasd"
  [162]=>
  string(0) ""
  [135]=>
  string(0) "awawawaw"
  [59]=>
  string(0) ""
  [63]=>
  string(0) ""
  [70]=>
  string(0) ""
  [146]=>
  string(0) ""
  [155]=>
  string(0) ""
  [66]=>
  string(0) ""

如果它包含任何内容,我想获取所有索引。你怎么做到这一点?我试过了

foreach($code_ids as $code_id) {
  if(!empty($code_id)) {
     $index[] = $code_id;
  }
}

问题在于它获得了它的价值。我只想要索引。

【问题讨论】:

    标签: php foreach key


    【解决方案1】:

    试试看

    array_keys(         // 2. returns keys as new array
        array_filter(   // 1. removes all empty items
            $code_ids));
    

    array_filter, array_keys

    【讨论】:

    • +1,但请注意 array_filter() 也会删除值为 0 或 false 的项目,甚至将 '0' 作为字符串删除。
    猜你喜欢
    • 2016-02-03
    • 1970-01-01
    • 2016-03-20
    • 2011-04-15
    • 1970-01-01
    • 2017-09-19
    • 2011-02-26
    • 1970-01-01
    • 2011-03-22
    相关资源
    最近更新 更多