Reputation: 21
I've got a one-dimensional array of objects that represent multi-dimensional data:
array(
array(
"id" => 1,
"parent_id" => 0,
"content" => 'des'
),
array(
"id" => 2,
"parent_id" => 3,
"content" => 'abc'
),
array(
"id" => 3,
"parent_id" => 1,
"content" => 'jjjj'
),
array(
"id" => 4,
"parent_id" => 5,
"content" => 'dsfsd'
),
array(
"id" => 5,
"parent_id" => 0,
"content" => 'dsfsd'
)
);
How should I convert it into a multi-dimensional array?
array(
array(
"id" => 1,
"parent_id" => 0,
"content" => 'des'
),
array(
"id" => 3,
"parent_id" => 1,
"content" => 'jjjj'
),
array(
"id" => 2,
"parent_id" => 3,
"content" => 'abc'
),
array(
"id" => 5,
"parent_id" => 0,
"content" => 'dsfsd'
),
array(
"id" => 4,
"parent_id" => 5,
"content" => 'dsfsd'
)
);
I'd like to sort by id and children after the parent, if parent_id = 0 it is the root element. Thanks everybody very much!
Upvotes: 1
Views: 126
Reputation: 21
this is my code (done)
function sort($array){
$newArray = [];
sortLoop($array, $newArray);
return $newArray;
}
function sortLoop($array, &$newArray, $parent_id = 0){
foreach ($array as $key => $item) {
if ($item['parent_id'] == $parent_id) {
$newArray[] = $item;
unset($array[$key]);
sortLoop($array,$newArray, $item['id']);
}
}
}
Wish this useful for someone.
Upvotes: 0
Reputation: 4499
I think you need to sort the array by parent_id
.
array_sort()
a laravel helper function : https://laravel.com/docs/5.7/helpers#method-array-sort
$sorted = array_sort($array, 'parent_id');
output
array:5 [▼
0 => array:3 [▼
"id" => 1
"parent_id" => 0
"content" => "des"
]
4 => array:3 [▼
"id" => 5
"parent_id" => 0
"content" => "dsfsd"
]
2 => array:3 [▼
"id" => 3
"parent_id" => 1
"content" => "jjjj"
]
1 => array:3 [▼
"id" => 2
"parent_id" => 3
"content" => "abc"
]
3 => array:3 [▼
"id" => 4
"parent_id" => 5
"content" => "dsfsd"
]
]
Upvotes: 2