嗨我有一个从foreach循环中得到的数组集合。它没有索引,我想修改它。
$productsRange = ProductPricesInventoryTax::where('sale_price', '>=', $min_price)
->where('sale_price', '<=', $max_price)
->get();
foreach($productsRange as $product){
$products = Product::where('id', '=', $product->product_id)->paginate(15);
$productDetails = $this->prepareAllProductDetails($products);
$array = $productDetails[0];//this returns the unidexed array
echo "<pre>";
print_r($array);
数组看起来像这样。
Array
(
[id] => 1
[sku] => 258
[name] => Bingo Mad Angles Chaat Masti
[is_configurable_product] => 1
[mrp] => 20
[sale_price] => 20
[image] => 258-bingo-mad-angles.jpeg
[brand] => Bingo
[configurable_attributes] => Array
(
[0] => Array
(
[child_product_id] => 2
[name] => Weight
[value] => 90 gms
[mrp] => 20
[sale_price] => 20
)
)
)
Array
(
[id] => 3
[sku] => 262
[name] => India Gate Basmati Rice-Rozana
[is_configurable_product] => 1
[mrp] => 620
[sale_price] => 444
[image] => 262-india-gate.jpeg
[brand] => India Gate
[configurable_attributes] => Array
(
[0] => Array
(
[child_product_id] => 4
[name] => Weight
[value] => 5 Kgs
[mrp] => 620
[sale_price] => 444
)
)
)
但是现在我希望数组看起来像这样在每个数组上都有数组索引。
Array
(
[0] => Array
(
[id] => 1
[sku] => 258
[name] => Bingo Mad Angles Chaat Masti
[is_configurable_product] => 1
[mrp] => 20
[sale_price] => 20
[image] => 258-bingo-mad-angles.jpeg
[brand] => Bingo
[configurable_attributes] => Array
(
[0] => Array
(
[child_product_id] => 2
[name] => Weight
[value] => 90 gms
[mrp] => 20
[sale_price] => 20
)
)
)
[1] => Array
(
[id] => 3
[sku] => 262
[name] => India Gate Basmati Rice-Rozana
[is_configurable_product] => 1
[mrp] => 620
[sale_price] => 444
[image] => 262-india-gate.jpeg
[brand] => India Gate
[configurable_attributes] => Array
(
[0] => Array
(
[child_product_id] => 4
[name] => Weight
[value] => 5 Kgs
[mrp] => 620
[sale_price] => 444
)
)
)
请帮忙。
答案 0 :(得分:0)
如果您尝试在PHP中声明一个数组,则需要添加一些内容。每个后续项目之间都需要逗号。此外,密钥不应该在括号中:
array(
"id" => 1,
"sku" => 258,
"name" => "Bingo Mad Angles Chaat Masti",
...,
"configurable attributes" => array(
0 => array(
"child_product_id" => 4,
"name" => "Weight",
...)
)
)
要创建数组数组,请使用类似的语法:
array(
1 => array(
"id" => 1, ... ),
2 => array(
"id" => 3, ... )
)
This site特别有帮助。 希望这有帮助!
答案 1 :(得分:0)
只需将$productDetails[0]
附加到新数组,然后将结果打印在foreach
$array[] = $productDetails[0]; //this returns the unidexed array
然后,在foreach
print_r($array);
除
外,您的所有代码都保持不变echo "<pre>";
print_r($array);
因为我们将输出移到了循环之外,所以不再需要了。