对象数组的索引数组

时间:2014-03-11 19:57:24

标签: php

如何创建(在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);

我想要一个新数组,其中" arr"是" eref_id"和" eref_child"但是数组的索引是" level"元件。所以基本上,

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

$arr[3](因为两者都有"等级"为3)。

这将包含$arr[2]$arr[3]的数组。

希望这是有道理的

2 个答案:

答案 0 :(得分:2)

您可以使用ouzo goodies

轻松完成

在php 5.4中:

$result = Arrays::toMap($arr, Functions::extract()['level']);

在php 5.3中:

$result = Arrays::toMap($arr, function($elem) { return $elem['level']; });

如果您有一个例如用户对象:

$cities = Arrays::map($users, Functions::extract()->getAddress('home')->city);

退房:http://ouzo.readthedocs.org/en/latest/utils/functions.html#extract

答案 1 :(得分:0)

<?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>';