0

我正在尝试使用 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);                    
    }
4

5 回答 5

0

您不能多次拥有相同的密钥。这是不可能的。数组必须有唯一的键。您可以为 name 键创建一个数组,它看起来像这样:

[ID] => Array
    (
        [NAME] => Array 
               (
                    [0] => QUANTITY
                    [1] => QUANTITY
               )
    )
于 2012-05-31T09:26:11.347 回答
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;
    }
}
于 2012-05-31T09:28:45.277 回答
0

试试这个代码:

<?php

$newArray = array();

foreach ($result as $value)
{
    $newArray[$value['id']] = array($value['NAME']=>$value['QUANTITY']);
}
于 2012-05-31T09:29:00.813 回答
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;
}
于 2012-05-31T09:29:58.880 回答
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);
    }
}
于 2012-05-31T10:18:24.807 回答