2

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

Juraj Blahunka
  • 17,913
  • 6
  • 34
  • 52
Itay Moav -Malimovka
  • 52,579
  • 61
  • 190
  • 278

4 Answers4

3

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
  • 28,143
  • 8
  • 66
  • 82
1

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
  • 17,913
  • 6
  • 34
  • 52
  • 1
    make here to post this. This is the way. There doesn't seem to be a built in function. – Mike Sherov Feb 05 '10 at 16:58
  • 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 Feb 05 '10 at 17:08
0

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
  • 41,754
  • 10
  • 52
  • 69
  • 1
    You can't set an array with `[` and `]` in PHP – Harmen Feb 05 '10 at 16:20
  • -1: he is talking about multi dim array, what if it goes deeper in level, how may foreach loops will you make? – Sarfraz Feb 05 '10 at 16:22
  • @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 Feb 05 '10 at 16:27
  • @Sarfraz Ahmed sorry, I wasn't paying attention to the first line :-D I was referring to `$arr[] = $item['id']` .. :) – Juraj Blahunka Feb 05 '10 at 16:48
-1

Maybe array_values(array_values($array));

Harmen
  • 22,092
  • 4
  • 54
  • 76