Taking keys from an array

Asked

Viewed 2,141 times

3

am ultilizando PDO for mysql query,and I would like to grab the keys of an array, tried several methods and failed, e.g.:$arr_cars['id'] an error has 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)
  • What are you trying to do? Why are you trying to create an identical array from another?

  • @Rodrigo Rigotti I made a select in the database that has 4 records and print the result

2 answers

7

If what you want is the matrix key, you should make use of the following syntax of foreach:

foreach (array_expression as $key => $value)

Thus, for each iteration, the element key is assigned to the first variable, and the element data is assigned to the second variable.

In your case I’d be:

$arr_cars = array();

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

   $arr_cars[] = $chave;
}

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

$arr_cars = array_keys($data);

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);
}
?>
  • Hat the problem is that in this database the user does Insert almost every day, imagines the job of editing the script when updating the keys, has another method?

  • 1

    @David this is the example to get the key, you will use it, after the select and of fetch_all, they are the ones who will generate the keys....

  • that’s what I was looking for, it worked perfectly

  • Could validate any of the answers, if correct. By clicking the green light below the assessment arrows.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.