(PHP)将数组数组从一种格式转换为另一种格式

时间:2010-06-17 09:07:36

标签: php arrays multidimensional-array

我目前有一个数组,是从数据库创建的,其示例如下所示:

Array(
    [0] => Array (
        objectid => 2,
        name => title,
        value => apple
    ),

    [1] => Array (
        objectid => 2,
        name => colour,
        value => red
    ),

    [2] => Array (
        objectid => 3,
        name => title,
        value => pear
    ),

    [3] => Array (
        objectid => 3,
        name => colour,
        value => green
    )
)

我想要做的是按照objectid对数组中的所有项进行分组,并将'name'值转换为keys,将'value'值转换为关联数组的值....如下所示:

Array (
    [0] => Array (
        objectid => 2,
        title => apple,
        colour => red
    ),

    [1] => Array (
        objectid => 3,
        title => pear,
        colour => green
    )
)

我尝试过一些东西,但实际上没有任何东西......有什么想法吗? 提前致谢

3 个答案:

答案 0 :(得分:0)

让数组键与您的对象id相对应会更容易,这样您就可以迭代现有数组,并为每个对象添加键值对,如下所示:

$newArray = array();
foreach ($results as $result) {

    if (!array_key_exists($result['objectid'], $newArray)) {
        $newArray[$result['objectid'] = array();
    }

    foreach ($result as $key => $value) {
        $newArray[$result['objectid'][$key] = $value;
    }
} 

答案 1 :(得分:0)

彼得的方法完全有效,我只是觉得我会展示同一件事的较短版本(在评论中无法做到)

foreach( $array as $obj ) {
    if( !isset( $objects[$obj['objectid']] ) )
        $objects[$obj['objectid']]['objectid'] = $obj['objectid'];

    $objects[$obj['objectid']][$obj['name']] = $obj['value'];
}

答案 2 :(得分:0)

这应该适用于您当前的设置,并且应该能够处理尽可能多的键值对:

<?php

$results = array(
    array('objectid' => 2, 'name' => 'title', 'value' => 'apple'), 
    array('objectid' => 2, 'name' => 'color', 'value' => 'red'),
    array('objectid' => 3, 'name' => 'title', 'value' => 'pear'), 
    array('objectid' => 3, 'name' => 'color', 'value' => 'green'));

$final = array();
foreach ($results as $result) {
    $final[$result['objectid']]['objectid'] = $result['objectid'];
    $final[$result['objectid']][$result['name']] = $result['value'];
}

print_r($final);