对象数组的索引数组

对象数组的索引数组

问题描述:

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

如何创建(在PHP中)和对象数组的数组? 例如,假设我有: p>

  $ 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); 
  code>  pre> 
 
 

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

  $ newarr [1]将包含$ arr [0] 
 $ newarr [2]将包含$ arr [1] 
 $ newarr [3] 将包含$ arr [2] 
  code>  pre> 
 
 

$ arr [3] code>(因为两者的“级别”均为3)。 p>

这将包含 $ arr [2] code>和 $ arr [3] code>的数组。 p> \ n

希望这是有道理的 p> div>

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

You can do it easily with ouzo goodies

In php 5.4:

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

In php 5.3:

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

If you had an array of e.g. User objects:

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

Check out: http://ouzo.readthedocs.org/en/latest/utils/functions.html#extract