Answer the question
In order to leave comments, you need to log in
How to iterate over an array?
Greetings!
There is an array
$data = array(
0 => array(
['id'] => 2,
['pagetitle'] => 'Главная',
['parent'] => 0
),
1 => array(
['id'] => 3,
['pagetitle'] => 'Категория',
['parent'] => 2
),
2 => array(
['id'] => 100,
['pagetitle'] => 'Подкатегория',
['parent'] => 5
),
);
Главная (id2)
-- Категория (id3)
-- Подкатегория (id5)
-- Подкатегория (id100)
-- Категория2 (id7)
-- Подкатегория (id55)
...
$category = array(
100 => array( // id подкатегории
['parent'] => 3, // id категории
['pagetitle'] => 'Категория',
),
5 => array( // id подкатегории
['parent'] => 3, // id категории
['pagetitle'] => 'Категория',
,
);
$category = array();
foreach ($data as $value) {
if ( $value['parent'] != 2 ) {
$parent = replaceParentCategory( $value, $data );
$category[$value['id']]['pagetitle'] = $parent['pagetitle'];
$category[$value['id']]['parent'] = $parent['id'];
} else {
$category[$value['id']]['pagetitle'] = $value['pagetitle'];
$category[$value['id']]['parent'] = $value['parent'];
}
}
function replaceParentCategory( $value, $data ){
foreach ($data as $item) {
if ( $value['parent'] == $item['id'] ){
if ( $item['parent'] == 2 ) return $value;
$value['parent'] = $item['parent'];
$value['pagetitle'] = $item['pagetitle'];
return replaceParentCategory( $value, $data );
}
}
}
$category = array(
100 => array( // id подкатегории
['parent'] => 100, // id категории
['pagetitle'] => 'Категория',
),
...
);
Answer the question
In order to leave comments, you need to log in
I did not quite understand the question, based on what you want to get - here is the code
$data = array(
0 => array(
'id' => 2,
'pagetitle' => 'Главная',
'parent' => 0
),
1 => array(
'id' => 3,
'pagetitle' => 'Категория',
'parent' => 2
),
2 => array(
'id' => 100,
'pagetitle' => 'Подкатегори 100',
'parent' => 5
),
3 => array(
'id' => 5,
'pagetitle' => 'Подкатегория 5 ',
'parent' => 2
)
);
$categories_array = array();
foreach ($data as $category) {
if (!in_array($category['id'], $categories_array)) {
$categories_array[$category['id']] = array();
$categories_array[$category['id']]['pagetitle'] = $category['pagetitle'];
$categories_array[$category['id']]['parent'] = $category['parent'];
}
}
echo '<pre>';
print_r($categories_array);
echo '</pre>';
How to get parent category data for all subcategories? Those. in subcategories with id100 , id5 data from category id3.
$data[$value['parent']]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question