PHP - 更新密钥的多维数组值

时间:2014-05-03 15:43:52

标签: php arrays multidimensional-array

我有以下数组:

 $sections = array(
                0 => array(
                    'id' => 'betrothed_details',
                    'name' => 'About us',
                    'order' => '1',
                    'menu_name' => '',
                    'display' => '1'
                ),
                1 => array(
                    'id' => 'events',
                    'name' => 'Events',
                    'display' => '1',
                    'order' => '2',
                    'menu_name' => ''
                ),
                2 => array(
                    'id' => 'gallery',
                    'name' => 'Gallery',
                    'order' => '3',
                    'menu_name' => '',
                    'display' => '1'
                ),
            );

我创建了拖放排序,wchich以正确的顺序传递id,如

$ids = array('events','betrothed_details','gallery')

对于每个$ ids数组,我需要更改order数组中相应的$sections值。

$i = 1;
foreach ($ids as $id) {

  CHANGE THE ORDER VALUE HERE to $i
  $i++;
}

这是怎么做到的?

1 个答案:

答案 0 :(得分:2)

试试这个:

<?php

$sections = array(
    0 => array(
        'id' => 'betrothed_details',
        'name' => 'About us',
        'order' => '1',
        'menu_name' => '',
        'display' => '1'
    ),
    1 => array(
        'id' => 'events',
        'name' => 'Events',
        'display' => '1',
        'order' => '2',
        'menu_name' => ''
    ),
    2 => array(
        'id' => 'gallery',
        'name' => 'Gallery',
        'order' => '3',
        'menu_name' => '',
        'display' => '1'
    ),
);
$ids = array('events', 'betrothed_details', 'gallery');
$sorted_sections = array();
foreach ($ids as $id) {
    foreach ($sections as $section) {
        if ($section['id'] == $id) {
            $sorted_sections[] = $section;
            break;
        }
    }
}
print_r($sorted_sections);

<强> Demo Link