M
M
Maxim Kushnir2016-09-17 20:38:16
Arrays
Maxim Kushnir, 2016-09-17 20:38:16

How to write a foreach loop for a given array?

There is an array that is output from the database

$firsts= array( 

1 => array(
    ['id'] => 1,
    ['title'] => '1',
    ['parent'] => 0,
    ['visible'] => 1,
    ['childs'] => array(
    
                        12 => array(
                                ['id'] => 12,
                                ['title'] => '1.1',
                                ['parent'] => 1,
                                ['visible'] => 1,
                                ['childs'] => array(
                                
                                                18 => array(
                                                    ['id'] => 18,
                                                    ['title'] => '1.1.1',
                                                    ['parent'] => 12,
                                                    ['visible'] => 1,
                                                    ['childs'] => array()
                                                    )
                                
                                
                                )),
                        
                        13 => array(
                                ['id'] => 13,
                                ['title'] => '1.2',
                                ['parent'] => 1,
                                ['visible'] => 1,
                                ['childs'] => array())
    
    
    
    )
),

2 => array(
    ['id'] => 1,
    ['title'] => '2',
    ['parent'] => 0,
    ['visible'] => 1,
    ['childs'] => array()
    )
)

and you need to make a selection from it
if they refer to the first subcategory, then loop to display the value of id and title
if to the subcategory of the subcategory, then also loop to display the value of id and title
here are my achievements and futile attempts
switch($query) {
     
      case 'getFirst':	// Запрос на получение 1ой подкатегории
    // Сохраним в переменную значение выбранного типа 
    $first_id = trim($_POST['first_id']); // Очистим его от лишних пробелов
    // Формируем массив с ответом
    $result = NULL;
    $i = 0;
    
        foreach($firsts[$first_id] as $kind_id => $kind)
        {
            $result[$i]['kind_id'] = $kind_id;
            
            foreach($kind['title'] as $value)
            {
                $result[$i]['kind'] = $value;
            }
            $i++;
        }
break;

and the key value must be $result[$i]['kind_id'] = $kind_id;
and its corresponding value named $result[$i]['kind'] = $value;
tell me something please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hoarywolf, 2016-09-17
@hoarywolf

a function with foreach and a recursive call to the same function when the key is childs

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question