views:

52

answers:

4

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

A: 

Maybe array_values(array_values($array));

Harmen
tested this piece of code and it won't work
Juraj Blahunka
A: 

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 ];
meouw
You can't set an array with `[` and `]` in PHP
Harmen
yes you can :-)
Juraj Blahunka
-1: he is talking about multi dim array, what if it goes deeper in level, how may foreach loops will you make?
Sarfraz
Also your first line of code is wrong
Sarfraz
@juraj.blahunka - Harmen is right, the first line is not legal PHP ( its pseudo code ;) ) @sarfraz-ahmed - when did you ever get an array more than two levels deep from a database result?
meouw
fixed the first line
meouw
@Sarfraz Ahmed sorry, I wasn't paying attention to the first line :-D I was referring to `$arr[] = $item['id']` .. :)
Juraj Blahunka
+2  A: 

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.

Ivan Nevostruev
+1 : exactly what the OP is asking for.
jeroen
A: 

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 ) );
?>
Juraj Blahunka
make here to post this. This is the way. There doesn't seem to be a built in function.
Mike Sherov
That´s not an answer to the question, the OP is asking for a build-in way in PHP or PDO and there is a way in PDO. See Ivan Nevostruev's answer.
jeroen