重构多维数组

时间:2011-08-17 15:46:55

标签: php arrays

我正在尝试重组一个数组,但无法弄清楚如何重新排列它以输出id作为键,我想改变这个:

Array
(
    [0] => Array
        (
            [0] => 16
            [1] => News
            [2] => News
            [3] => News
            [4] => News content
        )

    [1] => Array
        (
            [0] => 17
            [1] => about-us
            [2] => About us
            [3] => About us
            [4] => About us content

        )

)

对此:

Array
(
    [16] => Array
        (
            [0] => News
            [1] => News
            [2] => News
            [3] => News content
        )

    [17] => Array
        (
            [0] => about-us
            [1] => About us
            [2] => About us
            [3] => About us content

        )

)

1 个答案:

答案 0 :(得分:1)

我创建了这个演示脚本。这应该有用。

<?php

$original = array(0 => array(16, 'News', 'Etc'), 1 => array(35, 'Be', 'Here'));

foreach($original as $key => $value) {
  $new = array_shift($value);
  $newarray[$new] = $value;
}

echo '<pre>'.print_r($original,1).'</pre>';
echo '<pre>'.print_r($newarray,1).'</pre>';
?>

<强>输出:

Array
(
[0] => Array
    (
        [0] => 16
        [1] => News
        [2] => Etc
    )

[1] => Array
    (
        [0] => 35
        [1] => Be
        [2] => Here
    )

)

Array
(
[16] => Array
    (
        [0] => News
        [1] => Etc
    )

[35] => Array
    (
        [0] => Be
        [1] => Here
    )

)