在php中重建关联数组

时间:2012-05-31 09:24:05

标签: php arrays

我正在尝试使用foreach循环重新构造此数组:

Array
(
    [0] => Array
        (
            [ID] => 0
            [NAME] => 400
            [QUANTITY] => 12
        )

    [1] => Array
        (
            [ID] => 0
            [NAME] => 403
            [QUANTITY] => 108
        )

    [2] => Array
        (
            [ID] => 5
            [NAME] => 403
            [QUANTITY] => 108
        )
)

这就是我想要的样子:

Array
(
    [ID] => Array
        (
            [NAME] => QUANTITY
            [NAME] => QUANTITY
        )
Array
(
    [ID] => Array
        (
            [NAME] => QUANTITY
        )

我提出的代码无法正常工作,数组似乎在每个只显示最后一个条目的循环上被覆盖:

Array
(
    [ID] => Array
        (
            [NAME] => QUANTITY
        )
    [ID] => Array
        (
            [NAME] => QUANTITY
        )
)

这是我的代码:

$result = $sth->fetchAll(PDO::FETCH_ASSOC);

foreach($result as $key=>$value){
        $i = $value["ID"];
        $x = $value["NAME"];
        $y = $value["QUANTITY"]; 
        $arr[$i] = array( $x=>$y);                    
    }

5 个答案:

答案 0 :(得分:0)

你不能多次拥有相同的密钥。这是不可能的。数组必须具有唯一键。 你可以为name键创建一个数组,它将如下所示:

[ID] => Array
    (
        [NAME] => Array 
               (
                    [0] => QUANTITY
                    [1] => QUANTITY
               )
    )

答案 1 :(得分:0)

正如弗拉德所说,你不能使用相同的索引名......

但可能你想要这样的东西:

foreach($result as $key=>$value){
    $i = $value["ID"];
    $x = $value["NAME"];
    $y = $value["QUANTITY"];

    // here you go:
    $data = array($x => $y);
    if (isset($arr[$i]) {
        $arr[$i] = array_merge($arr[$i], $data);
    } else {
        $arr[$i] = $data;
    }
}

答案 2 :(得分:0)

试试这段代码:

<?php

$newArray = array();

foreach ($result as $value)
{
    $newArray[$value['id']] = array($value['NAME']=>$value['QUANTITY']);
}

答案 3 :(得分:0)

foreach($result as $key=>$value){
    $i = $value["ID"];
    $x = $value["NAME"];
    $y = $value["QUANTITY"]; 
    if(!isset($arr[$i])) $arr[$i] = array();
    $arr[$i][$x] = $y;
}

答案 4 :(得分:0)

我想这会有所帮助。考虑你声明你的数组。

$array = array(0 => array("id" => 0, "Name" => 400, "quantity" =>12),
                1 => array("id" => 0, "Name" => 403, "quantity" =>108),
                2 => array("id" => 5, "Name" => 403, "quantity" =>108)
);

并声明一个没有值或构造的新数组。

$newArray = array();

现在,试试这段代码!

foreach($array as $arr => $value)
{
    $id = $value["id"];
    $name = $value["Name"];
    $quantity = $value["quantity"];
    if(count($newArray[$id])>0){
        $newArray[$id] = array_merge($newArray[$id],array($name => $quantity));
    } else {
        $newArray[$id] = array($name => $quantity);
    }
}