phparrayspdoassociative-arrayfetchall

Fetch PDO results as associative array using two table columns


I'm trying to store data in an array from a database.

After printing the array, I need something like this :

Array ( [ABBA] => ?search=ABBA [ACDC] => ?search=ACDC [Ace of Spades] => ?search=AceOfSpades)

But currently, I have this :

Array ( [url] => ?search=ABBA [title] => ABBA ) Array ( [idtitle] => ?search=ACDC [title] => ACDC  ) Array ( [idtitle] => ?search=AceOfSpades [title] => Ace of Spades ) 

Here is my code to get the data and store into the array :

$key = $_POST['latestQuery'];

$requete = $bdd->prepare('SELECT url, title FROM articles WHERE title LIKE :key LIMIT 10');
$requete->execute(array('key' => '%'.$key.'%'));

$result_array[] = array();

foreach($requete->fetchAll(PDO::FETCH_ASSOC) as $search)
{
  print_r($result_array[$search['title']] = $search);
}

And here this my table structure :

url | title

$search=ACDC | ACDC

Do you think there is a way to formate my array?


Solution

  • Remove print_r from a foreach:

    $result_array = array();
    foreach($requete->fetchAll(PDO::FETCH_ASSOC) as $search)
    {
        $result_array[$search['title']] = $search['url'];
    }
    print_r($result_array);