Structure Array coming from mysql with PDO (organize)

0

Good evening, I'm having a difficulty with arrays where I'd like them to stay in order so I can use them as follows.

In my database I have many images that I call with this code below.

<?php $image_search = 00001::conect_sql();

$image_search = $image_search -> prepare("SELECT img_page, img_title, img_url FROM images ORDER BY img_id ASC");
$image_search -> execute();
$image_search = $image_search -> fetchAll();

foreach($image_search as $key => $img_link) { } ?>

With this code I can list all the images without any problems, but what I would like to do is create an array with the structure below.

id | title | link
0 | título da imagem 1 | link da imagem 1
1 | título da imagem 2 | link da imagem 2

and so on, as in the case of an array that would be

[0] => [img_title] - [img_url]
[1] => [img_title] - [img_url]

The reason I want to do this is to be able to use the $ img_link variable in an echo anywhere in the script using the following formatting.

echo $img_link[0][img_title] - $img_link[0][img_title]

echo $img_link[1][img_title] - $img_link[1][img_title]

echo $img_link[2][img_title]
echo $img_link[3][img_title]

where I will choose which image to use only by changing the key number [X]

I got more or less with this code

 $img_page_name[] = array($img_link['img_url']);

inside foreach

then with this

<?php echo $img_page_name[0][0];?>

where I want the image to appear.

Is there any better way to do this? one img_page = home would only display the last img_url that has img_page equal to home

    
asked by anonymous 09.10.2016 / 00:48

1 answer

1

Face makes a two-dimensional array, it's a main array with multiple arrays of two positions inside. I'll try to exemplify using your query:

<?php 

$imageSearch = 00001::conect_sql();

$imageSearch = $imageSearch -> prepare("SELECT img_page, img_title, img_url FROM images ORDER BY img_id ASC");
$imageSearch -> execute();
$imageSearch = $imageSearch -> fetchAll();

$ordena = [];
foreach($imageSearch as $key => $img) {
    $ordena['titulo'][] = $img['img_title'];
    $ordena['url'][] = $img['img_url'];
} 
print_r($ordena); 
/** A saída será uma lista de array com duas posições onde estas serão titulo e url com as colunas que você retornou do banco.
**/
?>

I do not remember now whether the PDO returns an array or an object, but the print_r in the variable that returns your query already informs you the type returned if it is object access the values of the variable as object ex: $ img-> ; img_title; $ img-> img_url;

I hope it helps, man, if you help, do not forget to accept the answer.

    
14.10.2016 / 16:02