Doing a foreach and ordering using $i++; for example but depending on a parent id in PHP
question updated:
I've the next array, obtained from a nested sortable tree. 开发者_StackOverflowThe $key
means the id of a PAGE and the $value
it's the parent id. In my MySQL table I've to modify the parent_id
of every page (when updating) and store the ORDER of a PAGE depending of the parent ID.
In the next example I've 3 ids with parent_id
= 1: 5, 2 and 3. I've to update on MySQL 5,2 and 3 saving like:
UPDATE pages SET parent_id=1,order=0 WHERE id=5
UPDATE pages SET parent_id=1,order=1 WHERE id=2
UPDATE pages SET parent_id=1,order=2 WHERE id=3
Array
(
[1] => 0
[5] => 1
[2] => 1
[3] => 1
[4] => 3
[6] => 3
)
How I can handle this with PHP? I'll do a foreach
for every page id and send a MySQL update on each of loop for the foreach
?
Thank you in advance!
I think you'll just want to use another variable to keep track of the last parent id used and then compare to see if it changed.
// make sure the array is sorted by parent id
asort($array);
$last_parent = -1;
foreach ($array as $id => $parent_id)
{
if ($last_parent != $parent_id)
$order = 0;
$query = 'UPDATE pages SET parent_id = ' . $parent_id . ', order = ' . $order . ' WHERE id = ' . $id;
$last_parent = $parent_id;
$order++;
}
Are you saying that you want to order the array based on the value?
In which case you would use
sort($array);
精彩评论