Get keys from an array

3

I am using PDO for mysql query, and I would like to get the keys from an array, tried several methods and did not succeed, ex: $arr_cars['id'] an error occurred

class Cars extends DB{
    static function getCars(){

    $select = self::getConn()->prepare('SELECT id,image,carro FROM 'cars'');
    $d = $select->fetchAll(PDO::FETCH_ASSOC);
    return $d;

    }
}
    //classe 

 $data = Cars::getCars();
 $arr_cars = array();

foreach($data as $key){ 
   $arr_cars[] = $key;
}

var_dump($cars);

/*irá imprimir:

array (size=4)
  0 => 
    array (size=3)
      'id' => string '1' (length=1)
      'image' => string '1.jpg' (length=5)
      'carro' => string 'bmw' (length=12)
  1 => 
    array (size=3)
      'id' => string '2' (length=1)
      'image' => string '2.jpg' (length=5)
      'carro' => string 'mercedes' (length=17)
  2 => 
    array (size=3)
      'id' => string '3' (length=1)
      'image' => string '3.jpg' (length=5)
      'carro' => string 'bentley' (length=9)
  3 => 
    array (size=3)
      'id' => string '4' (length=1)
      'image' => string '3.jpg' (length=5)
      'carro' => string 'volvo' (length=12)
    
asked by anonymous 14.07.2016 / 07:30

2 answers

1

You can use the key () function:

<?php
$array = array(
"one" => 1,
"two" => 2,
"three" => 3,
"four" => 4
);

while($element = current($array)) {
echo key($array)."\n";
next($array);
}
?>
    
14.07.2016 / 08:04
7

If you want the array key, you should use the following foreach :

foreach (array_expression as $key => $value)

So, at each iteration, the element key is assigned to the first variable, and the element data is assigned to the second variable.

In your case it would be:

$arr_cars = array();

foreach ($data as $chave => $dados) {

   $arr_cars[] = $chave;
}

Even more efficient is the array_keys function that takes over all the keys of a matrix:

$arr_cars = array_keys($data);
    
14.07.2016 / 11:00