0

我有闲置的多维数组结构:

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
            ...
4

3 回答 3

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);
于 2012-10-01T13:26:11.637 回答
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
于 2012-10-01T13:29:51.983 回答
0

当按唯一键分组时,PHP PDOfetchAll会产生类似的情况。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;
}

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

于 2019-01-04T07:19:31.250 回答