donglu3087 2014-03-11 19:57
浏览 6
已采纳

对象数组的索引数组

How do I create (in PHP) and array of an array of objects? For example, say I have:

$arr[0] = array("eref_id" => "A001", "eref_child" => "A100", "level" => 1);
$arr[1] = array("eref_id" => "A002", "eref_child" => "A200", "level" => 2);
$arr[2] = array("eref_id" => "A003", "eref_child" => "A300", "level" => 3);
$arr[3] = array("eref_id" => "A003", "eref_child" => "A310", "level" => 3);

An I want a new array where the elements of "arr" are the "eref_id" and "eref_child" but the index to the array is the "level" element. So basically,

$newarr[1] would contain $arr[0]
$newarr[2] would contain $arr[1]
$newarr[3] would contain $arr[2]

and $arr[3] (since both have a "level" of 3).

This would contain an array of $arr[2] and $arr[3].

Hopefully this makes sense

  • 写回答

2条回答 默认 最新

  • douluanzhao6689 2014-03-11 20:01
    关注
    <?php
    $arr[0] = array("eref_id" => "A001", "eref_child" => "A100", "level" => 1);
    $arr[1] = array("eref_id" => "A002", "eref_child" => "A200", "level" => 2);
    $arr[2] = array("eref_id" => "A003", "eref_child" => "A300", "level" => 3);
    $arr[3] = array("eref_id" => "A003", "eref_child" => "A310", "level" => 3);
    
    foreach($arr as $a){
        $newarr[$a['level']][] = $a;
    }
    
    echo '<pre>',print_r($newarr),'</pre>';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用