foreach循环里面的多维数组

时间:2014-06-19 02:08:15

标签: php arrays

我在print_r中有一个带有以下输出的数组$ new_items:

    Array
    (
        [0] => Array
            (
                [id] => 70494
                [weight] => 0.3000
                [Price] => 31.4400
                [url] => http://www.myshop.com
                [name] => Apple iphone
                [category] => Array
                    (
                        [parent_id] => Array
                            (
                                [0] => 53
                                [1] => 81
                            )

                        [parent_name] => Array
                            (
                                [0] => Mobile
                                [1] => Bluetooth  Devices
                            )

                        **[category_id] => Array
                            (
                                [0] => 150
                                [1] => 1384
                            )**

                        [category_name] => Array
                            (
                                [0] => iphone 4s
                                [1] => Bluetooth Speaker
                            )

                    )

                **[media] => Array
                    (
                        [images] => Array
                            (
                                [0] => http://www.myshop.com/file_2111_316.jpg
                                [1] => http://www.myshop.com/file_2112_260.jpg**

                            )

                    )

如何在另一个foreach循环中编写foreach循环,以便我可以获取所有值,包括[category_id]和[media] [images]值。

这是在两个单独的表中插入值。

我目前的代码是:

foreach($new_items as $key => $value) {
    $stmt = $conn->prepare("INSERT INTO   products(id,weight,price,cb_url,product_name) 
                            VALUES(:id,:weight,:price,:url,:name)");
    $stmt->execute(array(':id' => $value['id'], ':weight' => $value['weight'], ':price' => $value['Price'], ':url' => $value['url'],
                  ':name' => $value['name']));

    //second table insert
    $PID = $conn->lastInsertId();
    $stmt = $conn->prepare("INSERT INTO temp_products(productid,catid) 
                            VALUES(:pid,:catid)");
    $stmt->execute(array(':pid' => $PID, ':catid' => $value['category']['category_id']));
}

一切都很顺利,除了表2中的catid列正在插入值“array”,上面的[category_id]数组元素中有多个项目。如果只有1个项目,则正确插入。我需要同样插入[media] [images]。

我们是否需要在现有的foreach循环中编写foreach循环?或者如何继续?寻求帮助...

1 个答案:

答案 0 :(得分:0)

由于category_id是一个数组,因此您需要另一个foreach循环:

//second table insert
$PID = $conn->lastInsertId();
$stmt2 = $conn->prepare("INSERT INTO temp_products(productid, catid) VALUES(:pid, :catid)");
if (!is_array($value['category']['category_id'])) {
    $value['category']['category_id'] = array($value['category']['category_id']);
}
foreach ($value['category']['category_id'] as $catid) {
    $stmt2->execute(array(':pid' => $PID, ':catid' => $catid));
};

顺便提一下,请注意,您只需要在循环外准备一次语句。您应该使用第一个INSERT语句执行相同的操作。