1

我有一个用 php 开发的网站,我有一个函数,我想在其他数组中创建一个数组。我的查询是这样的(我正在使用 cakephp,但在这种情况下只是数组的问题,不要告诉我使用 cakephp 中的包含或类似的东西,因为它是一个大查询,我需要在其中构造我的查询和我的数组这种模式)

我的数组 $product_ingredient 包含一些值。

foreach ($product_ingredient as $key) {         
                $ingredient_level1 = $this->ProductIngredientVersion->query('SELECT * FROM ingredients_ingredients
                WHERE ingredients_ingredients.ingredient_id = :ingredient_id
                AND  ingredients_ingredients.product_id = :id 
                AND  ingredients_ingredients.version_id = :version_id 
                AND  ingredients_ingredients.level = 1', array('id' => $id, 'ingredient_id' => $key['products_ingredients']['ingredient_id'], 'version_id' => $key['products_ingredients']['version_id']));


                foreach($ingredient_level1 as $key2){
                    $ingredient_level2 = array($this->ProductIngredientVersion->query('SELECT * FROM ingredients_ingredients
                    WHERE ingredients_ingredients.ingredient_id = :ingredient_id
                    AND  ingredients_ingredients.product_id = :id 
                    AND  ingredients_ingredients.version_id = :version_id 
                    AND  ingredients_ingredients.level = 2', array('id' => $id, 'ingredient_id' => $key2['ingredients_ingredients']['ingredient2_id'], 'version_id' => $key2['ingredients_ingredients']['version_id'])));
                    array_push($ingredient_level1, $ingredient_level2);
                }
                array_push($ingredient_ingredient, $ingredient_level1);
            }

结果是:

array(
    (int) 0 => array(
        (int) 0 => array(
            'ingredients_ingredients' => array(
                'id' => '34',
                'level' => '1'
            )
        ),
        (int) 1 => array(
            (int) 0 => array(
                (int) 0 => array(
                    'ingredients_ingredients' => array(
                        'id' => '35',
                        'level' => '2'
                    )
                )
            )
        )
    )

但我想要这个结果

array(
    (int) 0 => array(
        (int) 0 => array(
            'ingredients_ingredients' => array(
                'id' => '34',
                'level' => '1',
                array(
                    'ingredients_ingredients' => array(
                        'id' => '35',
                        'level' => '2'
                    )
            )
        )
    )

我该如何解决?

4

1 回答 1

3

代替

array_push($ingredient_ingredient, $ingredient_level1);

经过

array_push(
    $ingredient_ingredient[0][0]['ingredients_ingredients'],
    $ingredient_level1
);

这会将阵列推到适当的级联级别。但是,如果您无法在其他地方修改 SQL 或数组结构,这很可能是最有效的方法。

于 2013-03-30T02:16:52.073 回答