我有一个用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'
)
)
)
)
我该如何解决?
答案 0 :(得分:3)
替换
array_push($ingredient_ingredient, $ingredient_level1);
通过
array_push(
$ingredient_ingredient[0][0]['ingredients_ingredients'],
$ingredient_level1
);
这会将数组推送到适当的级联级别。但是,如果您无法在其他地方修改SQL或数组结构,则很可能这是最有效的方式。