duanhuan7750 2015-03-13 21:48
浏览 31
已采纳

PHP将数组附加到子数组

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

  • 写回答

2条回答 默认 最新

  • douzhaochan6468 2015-03-13 21:50
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化