Rearranging multidimensional array in PHP [closed] Rearranging multidimensional array in PHP [closed] codeigniter codeigniter

Rearranging multidimensional array in PHP [closed]


It works in principle like this:

  1. You make each node identifiable by it's numeric id and store it in a hash so it's accessible by it's id.
  2. You take a new hash and insert all elements incl. their children as needed.

In detail discussion of the code is here: Converting an array from one to multi-dimensional based on parent ID values:

// key the array by id$keyed = array();foreach($array as &$value){    $keyed[$value['id']] = &$value;}unset($value);$array = $keyed;unset($keyed);// tree it$tree = array();foreach($array as &$value){    if ($parent = $value['parent_id'])        $array[$parent]['children'][] = &$value;    else        $tree[] = &$value;}unset($value);$array = $tree;unset($tree);var_dump($array); # your result

Replace the names with what you have as variable names and keys.


Create an array based on the pid from the current array which you can use to loop through the children based on the id.

$arr = array(...definition from your post....);foreach($arr["teams"] as $team)    $teamchildren[$team[pid]][]=$team;print_r($teamchildren);

Now you can loop through the $teamchildren[0] array and call a function recursively to build the nested team structure under each of the teams

The same concept could be applied to the players but changing the parent in this case to be the cid

(above code is not tested)