PHP Append an array to a sub array

六月ゝ 毕业季﹏ 提交于 2021-02-17 05:50:09

问题


I need to make an array of locations arrays, it must look like this

$relevanceKeys = array(
    'locations' => array(

        array(
            'longitude' => '123456',
            'latitude' => '123456'
        ),
        array(
            'longitude' => '123456',
            'latitude' => '123456'
        )
         ... more arrays
    )  

);

However I need to generate those on the fly, so it starts out like

$relevanceKeys = array(
    'locations' => array(  

    )  
);

And then I want to add each array from a row I found in the database:

while ($row = $result->fetch_object()) {
   $array = array(
               array (
       'longitude' => $row->longitude,
        'latitude' => $row->latitude
           )
   );

$relevanceKeys['locations'] = $relevanceKeys['locations'] + $array;
} 

This does not work though, afterwards the file is not readable. It's exported to a different format so I can't see if it turns into the array tree correctly.

I read how to append PHP arrays from here http://php.net/manual/en/function.array-merge.php

I tried unnested $array and nested in another array as it is now, no luck


回答1:


Just append the array like this:

$relevanceKeys['locations'][] = $array;
                         //^^ See here

You don't have to merge them all the time!

Also I think you want to change this:

$array = array(
             array (
                 'longitude' => $row->longitude,
                 'latitude' => $row->latitude
             )
       );

to this to get your expected structure:

$array = array(
             'longitude' => $row->longitude,
             'latitude' => $row->latitude
       );

For more information about array see the manual: http://php.net/manual/en/language.types.array.php




回答2:


Since you're only needing to push elements to the array, you can simply use the [] struct as follows:

while ($row = $result->fetch_object()) 
{
    $relevanceKeys['locations'][] = array (
        'longitude' => $row->longitude,
        'latitude' => $row->latitude
    );
} 


来源:https://stackoverflow.com/questions/29042542/php-append-an-array-to-a-sub-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!