使用foreach在数组内部创建数组

时间:2018-12-04 14:27:04

标签: php arrays multidimensional-array foreach dynamic-arrays

我只想在数组内部创建数组。创建此子数组后,我想用foreach填充它。

我想要什么:

(
[0] => Array
    (
        [Sıcak İçecekler] => Array
            (
                [foodId] => 1
                [foodName] => Food Name
                [foodPrice] => 15.25
            )

    )

[1] => Array
    (
        [Et Döner] => Array
            (
                [foodId] => 2
                [foodName] => Another Food From another Cat
                [foodPrice] => 6.75
            )

    ))

我的动态代码

    foreach ($categoryList as $cat) {
    $food = [
        $cat["catName"] => [
            foreach (Food::foodsByCategory($cat["catId"], $db) as $food):
                "foodId" => $food["foodId"],
                "foodName" => $food["foodName"],
                "foodPrice" => $food["foodPrice"]
            endforeach;
        ]   
    ];

    array_push($foodsByCategory, $food);
}
  

语法错误,意外的“ foreach”(T_FOREACH),期望为“]”

1 个答案:

答案 0 :(得分:1)

Afaik,PHP不支持此语法(将来的版本会很好..),因此您必须将foreach放在外面并创建一个临时数组。

$cat["catName"] => [
    foreach (Food::foodsByCategory($cat["catId"], $db) as $food):
        "foodId" => $food["foodId"],
        "foodName" => $food["foodName"],
        "foodPrice" => $food["foodPrice"]
    endforeach;
]

成为

$content = array();

// content creation
foreach (Food::foodsByCategory($cat["catId"], $db) as $food):
        content["foodId"] => $food["foodId"],
        content["foodName"] => $food["foodName"],
        content["foodPrice"] => $food["foodPrice"]
    endforeach;

// content insertion
$cat["catName"] = $content;

实际上,我发现去耦的创建和插入也更加清晰。