如何将此数组重组为不同结构的数组

时间:2014-07-31 18:05:02

标签: php arrays

我有一个如下所示的数组:

    [0] => Array
        (
            [name] => typeOfMusic
            [value] => this_music_choice
        )

    [1] => Array
        (
            [name] => myMusicChoice
            [value] => 9
        )

    [2] => Array
        (
            [name] => myMusicChoice
            [value] => 8
        )

我想将其改为大致具有以下结构的东西:

Array(
"typeOfMusic" => "this_music_choice",
"myMusicChoice" => array(9, 8)
)

我写了以下内容,但它不起作用:

    foreach($originalArray as $key => $value) {
        if( !empty($return[$value["name"]]) ){
            $return[$value["name"]][] = $value["value"];
        } else {
            $return[$value["name"]] = $value["value"];
        }
    }

    return $return;

我尝试了很多不同的组合来尝试让它发挥作用。我的原始数组可能包含几组需要转换为数组的键(即它并不总是只是" myMusicChoice"需要转换为数组)?

我无处可去,并希望得到一些帮助。非常感谢。

3 个答案:

答案 0 :(得分:3)

您只需要循环数据并使用名称/值创建一个新数组。如果看到重复名称,则将值更改为数组。

这样的事情:

$return = array();
foreach($originalArray as $data){
    if(!isset($return[$data['name']])){
        // This is the first time we've seen this name,
        // it's not in $return, so let's add it
        $return[$data['name']] = $data['value'];
    }
    elseif(!is_array($return[$data['name']])){
        // We've seen this key before, but it's not already an array
        // let's convert it to an array
        $return[$data['name']] = array($return[$data['name']], $data['value']);
    }
    else{
        // We've seen this key before, so let's just add to the array
        $return[$data['name']][] = $data['value'];
    }
}

DEMO:https://eval.in/173852

答案 1 :(得分:1)

这是一个干净的解决方案,使用array_reduce

$a = [
    [
        'name' => 'typeOfMusic',
        'value' => 'this_music_choice'
    ],
    [
        'name' => 'myMusicChoice',
        'value' => 9
    ],
    [
        'name' => 'myMusicChoice',
        'value' => 8
    ]
];

$r = array_reduce($a, function(&$array, $item){
    // Has this key been initialized yet?
    if (empty($array[$item['name']])) {
        $array[$item['name']] = [];
    }
    $array[$item['name']][] = $item['value'];
    return $array;
}, []);

答案 2 :(得分:1)

$arr = array(
    0 => array(
        'name'  => 'typeOfMusic',
        'value' => 'this_music_choice'
    ),
    1 => array(
        'name'  => 'myMusicChoice',
        'value' => 9
    ),
    2 => array(
        'name'  => 'myMusicChoice',
        'value' => 8
    )
);

$newArr = array();
$name = 'name';
$value = 'value';
$x = 0;
foreach($arr as $row) {
    if ($x == 0) {
        $newArr[$row[$$name]] = $row[$$value];
    } else {
        if (! is_array($newArr[$row[$$name]])) {
            $newArr[$row[$$name]] = array();
        }
        array_push($newArr[$row[$$name]], $row[$$value]);
    }       

    $x++;   
}