按阵列名称组数组

时间:2015-08-09 17:14:20

标签: php arrays

我有这个数组:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Something
            [other_id] => 2
            [other_name] => One
        )

    [1] => Array
        (
            [id] => 1
            [name] => Something
            [other_id] => 3
            [other_name] => Two
        )

    [2] => Array
        (
            [id] => 1
            [name] => Something
            [other_id] => 3
            [other_name] => Three
        )

    [3] => Array
        (
            [id] => 1
            [name] => Something
            [other_id] => 2
            [other_name] => Four
        )

)

现在我需要这个数组看起来像这样:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Something
            [0] => Array
                (
              [other_id] => 2
                  [other_name] => One
            )       
            [1] => Array
                (
              [other_id] => 3
                  [other_name] => Two
            )       
            [2] => Array
                (
              [other_id] => 4
                  [other_name] => Three
            )       
        )
)

我尝试了不同的方法但没有结果。我希望有人可以帮我一点点。

1 个答案:

答案 0 :(得分:2)

不确定我理解你想要什么,但这可能会这样做:

//Somewhere to store the result.
$output = array();

//Loop through the input array.
foreach($input as $element) {

    $id = $element['id'];
    $other_id = $element['other_id'];

    if(!isset($output[$id])) {
        //ID is not already in the output array, so add it.
        $output[$id] = array(
            'id' => $id,
            'name' => $element['name'],
        );
    }

    if(!isset($output[$id][$other_id])) {
        //Other_ID is not already in the output array, so add it.
        $output[$id][$other_id] = array(
            'other_id' => $other_id,
            'other_name' => $element['other_name'],
        );
    }

}