PHP:将多个关联数组添加到另一个数组

时间:2017-09-22 09:35:12

标签: php arrays

这是一个数据样本

Date  | Source | Amount
-----------------------
01A   | S1     | 12
01A   | S4     | 2
01A   | S7     | 134
02A   | S1     | 126
03A   | S4     | 10
02A   | S7     | 0
02A   | S1     | 3
02A   | S4     | 4
02A   | S7     | 5

结果数组需要如下所示:

Array
(
    [01A] => Array
        (
            [S1] => 12
            [S4] => 2
            [S7] => 134
        )
    [02A] => Array
        (
            [S1] => 126
            [S4] => 10
            [S7] => 0
        )
    [03A] => Array
        (
            [S1] => 3
            [S4] => 4
            [S7] => 5
        )
)

我已尝试查看PHP Adding multiple associative arrays to new array based on keyPHP multiple arrays to one associative arrayMerge multiple associative arrays to a single array of associative arrays等网页并使用以下代码(不使用相同的数据 - 但理论相同),但它没有生产我需要的东西。下面的代码只显示A和B

    $array = Array();
    $a=array( "ABC" => array("A"=>"RED","B"=>"GREEN"));
    $b=array( "ABC" => array("C"=>"BLUE","D"=>"YELLOW"));
    $array = $a + $b;
    echo '<pre>';
    print_r($array);
    echo '</pre>';

2 个答案:

答案 0 :(得分:1)

KISS

$result = array();
foreach($rows as $row)
{
    if(!isset($result[$row['Date']])) $result[$row['Date']] = array();
    $result[$row['Date']][$row['Source']] = $row['Amount'];
}

答案 1 :(得分:1)

假设您已经拥有$input数组中的数据,代码就像以下一样简单:

$result = array();
foreach ($input as $row) {
    $date = $row['Date'];
    if (! array_key_exists($date, $result)) {
        $result[$date] = array();
    }

    $result[$date][$row['Source']] = $row['Amount'];
}

如果您没有$input中的数据,但是从数据库中获取数据只需替换该行:

foreach ($input as $row) {

与您的数据检索循环相匹配的东西,例如:

while ($row = mysqli_fetch_assoc($result)) {