0

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

1
  • 2
    Surely you've tried something. Post it here. Commented Mar 11, 2014 at 19:59

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.