(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));
精彩评论