Structure Array coming from mysql with PDO (organize)

Asked

Viewed 287 times

0

Good evening, I’m having a hard time 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 them 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 to 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 in an array that would be

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

Why I want to do this is so I can 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 just by changing the key number [X]


I sort of got it with this code

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

inside the foreach

then with this

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

in the place I wish the image to appear.

Is there a better way to do that? a cool thing would also be to run an if at the time of picking up the image, each image has an img_page in the case, in img_page = home would only display the last img_url that has the img_page equal to home

1 answer

1


Cara makes a two-dimensional array, is a main array with several two-position arrays inside. I will 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 don’t remember now if the PDO returns an array or an object, but the print_r in the variable that returns your query already tells 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 it helps, don’t forget to accept the answer.

  • I will be as soon as I get back from work and give you the feedback, but it seems to work.

Browser other questions tagged

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