Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping off of MySQL result and building custom array

Tags:

php

mysql

The following code is building the proper structure of array that I want, but it's only doing it for one result even though the MYSQL result is about 65 items.

I need the 'type' and 'features' levels to be static, and then start the loop within the features level (so every mysql result would build an item in within the features level)

The following is only loading the last result from the query:

$db->setQuery($query);
$item=$db->loadObjectList();
echo $db->getErrorMsg();
//dump($item);

$stores = [
    'type' => 'FeatureCollection',
    'features' => [
      foreach ($item as $i) {
        [
            'type' => 'Feature',
            'geometry' => [
                'type' => 'Point',
                'coordinates' => [
                    $i->lat,
                    $i->lng
                ]
            ],
            'properties' => [
                'storeImage' => $i->logo, // you need to convert this into an actual URL
                'storeName' => $i->name,
                'phoneFormatted' => $i->phone, // this needs formatting aswell
                'address' => $i->address,
                'city' => $i->city,
                'country' => $i->country,
                'postalCode' => $i->zip,
                'state' => $i->state
            ]
        ]
      }
    ]
];

How can I properly loop the mysql query to build my array in the correct way?

like image 234
Geoff_S Avatar asked Dec 20 '25 10:12

Geoff_S


1 Answers

Use array_map() to generate a new array from another array.

$item=$db->loadObjectList();

$stores = [
    'type' => 'FeatureCollection',
    'features' => array_map(function($i) {
        return [
            'type' => 'Feature',
            'geometry' => [
                'type' => 'Point',
                'coordinates' => [
                    $i->lat,
                    $i->lng
                ]
            ],
            'properties' => [
                'storeImage' => $i->logo, // you need to convert this into an actual URL
                'storeName' => $i->name,
                'phoneFormatted' => $i->phone, // this needs formatting aswell
                'address' => $i->address,
                'city' => $i->city,
                'country' => $i->country,
                'postalCode' => $i->zip,
                'state' => $i->state
            ]
        ];
    }, $item)
];
like image 139
Barmar Avatar answered Dec 22 '25 23:12

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!