Viewed   85 times

I have a list of categories in MySQL with parent ID. How can I create a PHP array from the list.

ID  Category      Parent_ID
1   Car           NULL
2   Education     NULL
3   Mathematics   2
4   Physics       2
5   Astrophysics  4

I want to produce an array of this structure

array(
    "Car" => "1",
    "Education" => array("Mathematics" => "2", "Physics" => array("Astrophysics" => "4"))
);

As a matter of fact, key/value is not important as I will work with other columns too. I just want to know how to scan the list and produce multi-level list.

 Answers

1

Some very simple recursion to build a tree structure:

function buildTree(array $data, $parent = null) {
    $branch = array();

    foreach ($data as $row) {
        if ($row['parent_id'] == $parent) {
            $row['children'] = buildTree($data, $row['id']);
            $branch[] = $row;
        }
    }

    return $branch;
}

$tree = buildTree($rowsFromDatabase);

Having an explicit 'children' key is usually preferable to the structure you're proposing, but feel free to modify as needed.

Thursday, October 20, 2022
4

You need to iterate over your results, adding a new entry to the output when you encounter a new team, or updating the points value when you find the same team again. This is most easily done by initially indexing the output by the team name, and then using array_values to re-index the array numerically:

$teams = array();
foreach ($results as $result) {
    $team = $result['team'];
    if (!isset($teams[$team])) {
        $teams[$team] = array('team' => $team, 'points' => $result['punti']);
    }
    else {
        $teams[$team]['points'] += $result['punti'];
    }
}
$teams = array_values($teams);
print_r($teams);

Output (for your sample data):

Array
(
    [0] => Array
        (
            [team] => Red Bull Racing
            [points] => 418
        )
    [1] => Array
        (
            [team] => Scuderia Ferrari
            [points] => 353
        )
    [2] => Array
        (
            [team] => Mercedes-AMG
            [points] => 516
        )
    [3] => Array
        (
            [team] => Racing Point F1
            [points] => 147
        )
    [4] => Array
        (
            [team] => Haas F1
            [points] => 127
        )
)

Demo on 3v4l.org

Friday, August 12, 2022
 
4

Might be more complex than needed but maybe a combination:

$array = array_map(function($v) {
                   return array_filter($v, function($v) {
                                           return $v['foo'] === 'bar'; }); }, $array);

This should also work:

foreach($array as &$value) {
    $value = array_filter($value, function($v) { return $v['foo'] === 'bar'; });
}

You can use a recursive function for deeper or unknown nesting:

function filterNotSomething(&$array, $key, $val) {
    foreach($array as $k => $v) {            
        if(isset($v[$key]) && $v[$key] !== $val) {
            unset($array[$k]);
        }
        elseif(is_array($v)) {
            filterNotSomething($array[$k], $key, $val);
        }
        if(empty($array[$k])) {
            unset($array[$k]);
        }
    }
}

filterNotSomething($array, 'foo', 'bar');
Saturday, September 24, 2022
3

You can do it based on array_column():-

<?php

$array = [[5, 4, 10], [11, 13, 15], [32, 14, 15]];

$final_array = [array_column($array,0),array_column($array,1),array_column($array,2)];

print_r($final_array );

Output:-https://eval.in/836310

Note:- above code will work only for this array.

More general and considering all aspects code is using foreach():-

<?php
$array = [[5, 4, 10], [11, 13, 15], [32, 14, 15]];

$final_array = array();

foreach($array as $arr){
    foreach($arr as $key=>$value){
      $final_array[$key][]=$value;
    }
}
print_r($final_array);

Output:- https://eval.in/836313

Sunday, December 4, 2022
 
3

You can do it like this, do the calculation from the innermost of the array. Check the demo.

<?php
function f(&$array)
{
    foreach($array as $k => &$v)
    {
        if(is_array($v))
        {
            if(count($v) == count($v, 1))
            {
                unset($array[$k]);
                if($k == 'sum')
                {
                    $v =  array_sum($v);
                    $array[] = $v;

                }elseif($k == 'multiply'){
                    $v = array_product($v);
                    $array[] = $v;
                }else{

                    foreach($v as $vv)
                        $array[] = $vv;
                }
            }else
                f($v);
        }
    }
}

while(count($array) != count($array, 1))
{
    f($array);
}

print_r($array);

Noteļ¼š

traverse array from outer to inner
traverse array from inner to outer

Monday, November 14, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :