从Foreach创建数组

时间:2012-02-15 13:53:30

标签: php arrays foreach

我有一个Mysql表,其中包含一列JSON数据和一个包含金额的列。 目标是提取JSON数据和数量,并在foreach循环中构建一个数组。 这是我的代码:

$sql = "SELECT `Amount`, `NewObject` FROM `mb_cart` WHERE `MyID` = '$id'";
$data_main = $db->query($sql);

以下是我用于构建数组的声明:

foreach ($data_main as $transaction_main) {
    $json_decoded = json_decode($transaction_main);
    $cart = array('Amount' => $amount, 'CodeType' => $json_decoded->data->Type->data->codeType, 'Name' => $json_decoded->data->Name, 'SiteName' => $json_decoded->data->SiteName);
}

然而,当我运行它时,我只返回第一个记录集,且数量为空,但列出了JSON数据。欣赏任何人关心分享的见解。

5 个答案:

答案 0 :(得分:24)

您需要将[]添加到$cart数组。每次运行foreach都会覆盖变量$ cart。

类似的东西会起作用:

foreach ($data_main as $transaction_main) {
    $json_decoded = json_decode($transaction_main);
        $cart[] = array('Amount' => $amount, 'CodeType' => $json_decoded->data->Type->data->codeType, 'Name' => $json_decoded->data->Name, 'SiteName' => $json_decoded->data->SiteName);
    }

或者,如果您希望数组键与每行的ID匹配:

注意:您需要在IE上方设置$ id变量:SELECT id, amount还要注意,如果来自id的整数是非唯一的,则可能会出现问题。例如(1,1,2,3,4,5,6)它只会显示1的最后一个ID而不是两者(因为密钥是重复的)。

foreach ($data_main as $transaction_main) {
    $json_decoded = json_decode($transaction_main);
        $cart[$id] = array('Amount' => $amount, 'CodeType' => $json_decoded->data->Type->data->codeType, 'Name' => $json_decoded->data->Name, 'SiteName' => $json_decoded->data->SiteName);
    }

答案 1 :(得分:10)

您的变量$cart在每个循环中都被覆盖,因为您每次都在调用array()

相反,在循环外声明您的数组,只需根据需要为其添加值:

$cart = array();
foreach ($data_main as $transaction_main) {
    $json_decoded = json_decode($transaction_main);
    $cart[] = array('Amount' => $amount, 'CodeType' => $json_decoded->data->Type->data->codeType, 'Name' => $json_decoded->data->Name, 'SiteName' => $json_decoded->data->SiteName);
}

答案 2 :(得分:5)

$cart = array();

foreach ($data_main as $transaction_main) {
    $json_decoded = json_decode($transaction_main);
    $cart[] = array('Amount' => $amount, 'CodeType' => $json_decoded->data->Type->data->codeType, 'Name' => $json_decoded->data->Name, 'SiteName' => $json_decoded->data->SiteName);
}

print_r($cart);

答案 3 :(得分:5)

试试这个:

$cart=array();
foreach ($data_main as $transaction_main) {
    $json_decoded = json_decode($transaction_main);
        $cart[] = array('Amount' => $amount, 'CodeType' => $json_decoded->data->Type->data->codeType, 'Name' => $json_decoded->data->Name, 'SiteName' => $json_decoded->data->SiteName);
    }

您将购物车视为变量而非数组

答案 4 :(得分:0)

接近此方法首先创建一个变量$cart = array(); 然后做foreach(); 我已经编写了以下代码,请仔细阅读

foreach($data_main as $transaction_main){
    $json_decoded = json_decoded($transaction_main);
    $cart[]=array('Amount' => $amount, 'CodeType' => $json_decoded->data->Type->data->codeType, 'Name' => $json_decoded->data->Name, 'SiteName' => $json_decoded->data->SiteName);
}