Reputation: 15
I have a PHP array of categories like this
$category = array(
1 => array(
'id' => 1,
'parentID' => 0,
'name' => 'SUV auto parts'
),
2 => array(
'id' => 2,
'parentID' => 1,
'name' => 'Engine Related'
),
3 => array(
'id' => 3,
'parentID' => 2,
'name' => 'Spark Plugs'
),
4 => array(
'id' => 4,
'parentID' => 2,
'name' => 'Engine Oil'
),
5 => array(
'id' => 5,
'parentID' => 1,
'name' => 'Body related'
),
6 => array(
'id' => 6,
'parentID' => 0,
'name' => 'Sedan auto parts'
),
7 => array(
'id' => 7,
'parentID' => 6,
'name' => 'Engine Related'
),
);
I have no idea how to get this done just by using PHP array without MYSQL query, trying to display sub-categories where 'parentID' = supplied category ID
for example when category id 1 is requested, I wanna list name and html link for category 2 and 5, when category id 2 is requested, I wanna display name and html link for category 3 and 4
SUV auto parts
Sub-categories; Spark Plugs Engine Oil
likewise when "Engine Related" page is requested
Engine Related
Sub-categories; Engine Related Body related
I appreciate if someone will give any solution.
Upvotes: 0
Views: 107
Reputation: 1205
More sophisticated approaches exist surely, but a solution that is easy to understand and tailor(e.g. prettify) to your use case, is the following:
$parentId = 2; // set the parentID
foreach($category as $key => $value) {
if($value['parentID'] == $parentId) {
echo '<pre>';
print_r($value); // print matching record
echo '</pre>';
}
}
working demo
Upvotes: 1