在php中展开二级数组

时间:2012-10-01 13:23:08

标签: php multidimensional-array

我有以下多维数组结构:

array
  '2012-10-02' => 
     array
       0 => 
        array
          'item1' => 
            array
              ...

   '2012-10-03' => 
     array
       0 => 
         array
           'item1' => 
             array
               ...

如何解开Item数组,以便结构如下:

array
  '2012-10-02' => 
     array
       'item1' => 
          array
           ...
   '2012-10-03' => 
      array
        'item1' => 
          array
            ...

3 个答案:

答案 0 :(得分:3)

您需要遍历数组,并为每个项目“提升”$item[0]$item曾经拥有的地方。例如:

foreach($input as &$element) {  // by reference!
    $element = $element[0];
}

// not strictly required, but prevents you from accidentally messing with
// $element outside of the loop (which would almost certainly be a bug)
unset($element);

答案 1 :(得分:0)

您应该尝试使用array_map返回第一个元素

$array = array("2012-10-02" => array(array("item1"=>array())),"2012-10-03" => array(array("item1"=>array())));

#before
var_dump($array);

$array = array_map(function($var) {return $var[0];} , $array);

#after
var_dump($array);

array
  '2012-10-02' => 
    array
      0 => 
        array
          'item1' => 
            array
              ...
  '2012-10-03' => 
    array
      0 => 
        array
          'item1' => 
            array
              ...

之后

array
  '2012-10-02' => 
    array
      'item1' => 
        array
          empty
  '2012-10-03' => 
    array
      'item1' => 
        array
          empty

答案 2 :(得分:0)

带有fetchAll的PHP PDO PDO::FETCH_GROUP在按唯一键分组时会导致类似情况。原样使用结果需要进行数据访问,例如$rows['key_1'][0]['data_1']。下面的循环摆脱了多余的包装器数组。然后可以像$rows['key_1']['data_1']一样访问相同的数据。

public function get_unique_assoc_rows() {
    $stmt = $this->pdo->prepare('SELECT assoc_key, other_field'
            . ' FROM some_table');
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_GROUP);

    foreach ($rows as &$row) {
        $row = $row[0];
    }
    return $rows;
}

注意:对于非唯一键,请不要这样做,因为您需要包装器数组。