Reputation: 1029
Not having much luck creating a sub array, partially because I don't fully grasp how keys work.
Here is what I am trying to do:
$sql = "select * from products";
$db->query($sql);
$products = $db->rows();
foreach($products as $key=>$row) {
$sql = "select * from sub_products WHERE productid = " . (int)$row['ID'] . "";
$db->query($sql);
$subproducts = $db->rows();
$products[$key]['subproducts'] = $subproducts;
foreach($products[$key]['subproducts'] as $rr=>$x) {
$sql = "select * from subsubproducts WHERE subproducts = " . (int)$x['ID'] . "";
$db->query($sql);
$subsubproducts = $db->rows();
$products[$key]['subproducts']['subsubproducts'] = $subsubproducts;
}
}
I am not really grasping the concept of keys here and so therefore I am having a hard time understanding how to insert sub-arrays into other sub-arrays.
Currently, the code above, instead of placing the subsubproducts array as an array/item within the subproducts array, it is tagging it on as another item/array. i.e. under subproducts you have:
subproduct1
subproduct2
subsubproducts
Whereas it should be:
subproduct1
---subsubproductslisting
subproduct2
---subsubproductslisting.
Upvotes: 0
Views: 76
Reputation: 5700
You are properly adding depth to the arrays, your logical context is just off.
foreach($products[$key]['subproducts'] as $key=>$row)
will assign the index to $key
and the value to $row
for each iteration.
foreach($products[$key]['subproducts'] as $rr => $x)
will assign the index to $rr
and the value to $x
for each iteration.
When you assign to $products[$key]['subproducts']['subsubproducts']
you are assigning a value to the key subsubproducts
at the subproducts
level.
Changing the assignment to:
$products[$key]['subproducts'][$rr]['subsubproducts'] = $subsubproducts;
should give you the desired result.
Upvotes: 1
Reputation: 13344
If I follow your train of thought, it should be as easy as identifying the key and using it in the second loop to identify the correct array.
$products[$key]['subproducts'][ $rr ]['subsubproducts'] = $subsubproducts;
In context:
$sql = "select * from products";
$db->query($sql);
$products = $db->rows();
foreach($products as $key=>$row) {
$sql = "select * from sub_products WHERE productid = " . (int)$row['ID'] . "";
$db->query($sql);
$subproducts = $db->rows();
$products[$key]['subproducts'] = $subproducts;
foreach($products[$key]['subproducts'] as $rr=>$x) {
$sql = "select * from subsubproducts WHERE subproducts = " . (int)$x['ID'] . "";
$db->query($sql);
$subsubproducts = $db->rows();
$products[$key]['subproducts'][ $rr ]['subsubproducts'] = $subsubproducts;
}
}
Upvotes: 2
Reputation: 1326
You've almost got it you just need to do replace this:
$products[$key]['subproducts']['subsubproducts'] = $subsubproducts;
with this:
$products[$key]['subproducts'][$rr]['subsubproducts'] = $subsubproducts;
In the second foreach loop
Upvotes: 3