有一种内置的方法可以在PHP中从多维数组中获取数组吗?

有一种内置的方法可以在PHP中从多维数组中获取数组吗?

问题描述:

(Very useful when querying DB).
If I have a multy dim array

 [['id'=>1],['id'=>2],['id'=>34],['id'=>67]]

and what I want is [1,2,34,67]

I know how to do it in code, just asking if there is a built in way in PHP (or may be in PDO) to do this.

(查询数据库时非常有用)。
如果我有一个multy dim数组 p> \ n

  [['id'=> 1],['id'=> 2],['id'=> 34],['id'=> 67]]  
  code>  pre> 
 
 

我想要的是 [1,2,34,67] code> p>

I 知道如何在代码中执行此操作,只是询问PHP中是否存在内置方式(或者可能在PDO中)来执行此操作。 p> div>

I think you need PDO::FETCH_COLUMN mode in fetchAll, which returns only a single column as array:

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the values of the first column */
$result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
var_dump($result);
?>

From the manual:

To return an array consisting of all values of a single column from the result set, specify PDO::FETCH_COLUMN. You can specify which column you want with the column-index parameter.

Maybe array_values(array_values($array));

Could you not just make the array you want?

$old = array( array( 'id'=>1 ), array( 'id'=>2 ), array( 'id'=>34 ), array( 'id'=>67 ) );
$arr = array();
foreach( $old as $item ) {
    $arr[] = $item['id'];
}

//$arr = [ 1, 2, 34, 67 ];

a very easy way is to flatten your multi dimensional array

this code was extracted from http://php.net/manual/en/function.array-values.php

<?php 
  function array_flatten($array, $flat = false) 
  { 
    if (!is_array($array) || empty($array)) return ''; 
    if (empty($flat)) $flat = array(); 

    foreach ($array as $key => $val) { 
      if (is_array($val)) $flat = array_flatten($val, $flat); 
      else $flat[] = $val; 
    } 

    return $flat; 
  } 

  // will get your flattened array
  print_r( array_flatten( $vals ) );
?>