dongsu0308 2017-07-11 19:31
浏览 58
已采纳

使用基于现有多维数组PHP的附加键创建新数组

So I got an array like:

Array
(
    [0] => Array
        (
            [ids] => Array
                (
                    [id] => id1
                )

            [name] => name1
            [number] => 1
        )

    [1] => Array
        (
            [ids] => Array
                (
                    [id] => id2
                )

            [name] => name2
            [number] => 2
        )
)

And I want to construct new multidimensional array based on the elements of it, but adding some new keys with empty values like(all the keys will have other names in new array, it's just simplified):

Array
(
    [0] => Array
        (
            [id] => id1
            [firstname] => name1
            [lastname] => 
            [somedata] => 
            [somemoredata] => 
            [ordernumber] => 1
         )
    [1] => Array
        (
            [id] => id2
            [firstname] => name2
            [lastname] => 
            [somedata] => 
            [somemoredata] => 
            [ordernumber] => 2
         )
)

How do I do it? Was thinking about array_push inside foreach loop, but it's not gonna do the job because of the empty keys I want and different order of elements. I also know how to access the nested value of [id] but still no idea about how to construct and move values to the new array for each element.

  • 写回答

1条回答 默认 最新

  • dongpu5600 2017-07-11 19:38
    关注

    You can do it like below:-

    $final_array = array();
    foreach($array as $arr){
        $final_array[] = array('id'=>$arr['ids']['id'],'firstname'=>$arr['name'],'lastname'=>'','somedata'=>'','somemoredata'=>'','ordernumber'=>$arr['number']);
    }
    print_r($final_array);
    

    Output:-https://eval.in/831090

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程