开发者

Is there a built in way to get an array out of multi dim array in PHP? [duplicate]

This question already has answers here: 开发者_运维问答 Is there a function to extract a 'column' from an array in PHP? (15 answers) Closed 5 months ago.

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


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.


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 ) );
?>


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 ];


Maybe array_values(array_values($array));

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜