Viewed   90 times

I'm new to arrays in PHP and am trying to wrap my mind around how to make a multidimensional associative array. I'd like the array to look like this when I use print_r:

Array ( [0] => Array ( [alert] => alert [email] => Test ) )

Instead I get this:

Array ( [0] => Array ( [alert] => Array ( [email] => Test ) ) )

The code I'm using is this:

$alert_array = array();

$alert_array[]["alert"]["email"] = "Test";

I thought trying something like this would work, but obviously my syntax is a bit off. I think I'm somewhat on the right track though?:

$alert_array[][["alert"]["email"]] = "Test";

Thank for your help (sorry if this is super basic, I couldn't find any questions that addressed this exactly)!

 Answers

3
$alert_array = array();
$alert_array[] = array('alert' => 'alert', 'email' => 'Test');
...
var_dump($alert_array);

In your case you'd have to specify key like so:

$alert_array[$key]["alert"] = "alert";
$alert_array[$key]["email"] = "Test";

You'd have to have a loop with counter too.

If you're using PHP 5.4+ you could use short array syntax:

$alert_array = [];
$alert_array[] = ['alert' => 'alert', 'email' => 'Test'];
Sunday, September 18, 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
 
2
foreach($schoolDetails as $schoolDetail) {
    echo "<tr>";
    echo "<td>{$schoolDetail[0]["schoolName"]}</td>";
    echo "<td>{$schoolDetail[1]["branchName"]}</td>";
    echo "<td>{$schoolDetail[1]["phone"]}</td>";
    echo "<td>{$schoolDetail[1]["numberofTeachers"]}</td>";

    if(!empty($schoolDetail[3]['departmentName'])) {

        echo "<td>{$schoolDetail[2]["departmentName"]}" . ", " . "{$schoolDetail[3]["departmentName"]}</td>"; 

    } else {

        echo "<td>{$schoolDetail[2]["departmentName"]}</td>";

    }

    if(!empty($schoolDetail[3]['HOD'])) {

        echo "<td>{$schoolDetail[2]["HOD"]}" . ", " . "{$schoolDetail[3]["HOD"]}</td>"; 

    } else {

        echo "<td>{$schoolDetail[2]["HOD"]}</td>"; 
    
    }

    echo "</tr>";
}
Tuesday, October 11, 2022
 
3

This may help you

Script - For csv to array from file

[akshay@localhost tmp]$ cat test.php
<?php

function csv_to_array($filename='', $delimiter=',')
{
    if(!file_exists($filename) || !is_readable($filename))
        return FALSE;

    $header = NULL;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 0, $delimiter)) !== FALSE)
        {

            if(!$header)
            {
               $header = $row;
            }
            else
            {
                if(count($header)!=count($row)){ continue; }

                $data[] = array_combine($header, $row);
            }
        }
        fclose($handle);
    }
    return $data;
}

print_r(csv_to_array("/tmp/test.csv"));

?>

Script - For csv to array from string

[akshay@localhost tmp]$ cat test.php
<?php

function str_to_csv_to_array($string, $delimiter=',')
{
        $header = NULL;
        $data = array();
        $rows = explode(PHP_EOL, $string); 
        foreach($rows as $row_str)
        {
            $row = str_getcsv($row_str);
            if(!$header)
            {
               $header = $row;
            }
            else
            {
                if(count($header)!=count($row)){ continue; }

                $data[] = array_combine($header, $row);
            }
        }

    return $data;
}


$string = <<<EOF
date,time,label,artist,composer,album,title,duration
2015-06-16,12:00 AM,Island,U2,"Clayton- Adam,The Edge,Bono,Mullen- Larry- Jr",Songs Of Innocence,SONG FOR SOMEONE,03:46
2015-06-16,12:04 AM,Lowden Proud,"Fearing & White, Andy White, Stephen Fearing","White- Andy,Fearing- Stephen",Tea And Confidences,SECRET OF A LONG LASTING LOVE,03:10
2015-06-16,12:07 AM,Columbia,The Wallflowers,"Dylan- Jakob,Irons- Jack,Mathis- Stuart,Richling- Greg,Jaffee- Rami",Glad All Over,REBOOT THE MISSION,03:31
2015-06-16,12:10 AM,Distort Light,Bend Sinister,Moxon- Daniel,"Stories Of Brothers, Tales Of Lovers",JIMMY BROWN,03:48
EOF;

print_r(str_to_csv_to_array($string));
?>

Input file

[akshay@localhost tmp]$ cat test.csv
date,time,label,artist,composer,album,title,duration
2015-06-16,12:00 AM,Island,U2,"Clayton- Adam,The Edge,Bono,Mullen- Larry- Jr",Songs Of Innocence,SONG FOR SOMEONE,03:46
2015-06-16,12:04 AM,Lowden Proud,"Fearing & White, Andy White, Stephen Fearing","White- Andy,Fearing- Stephen",Tea And Confidences,SECRET OF A LONG LASTING LOVE,03:10
2015-06-16,12:07 AM,Columbia,The Wallflowers,"Dylan- Jakob,Irons- Jack,Mathis- Stuart,Richling- Greg,Jaffee- Rami",Glad All Over,REBOOT THE MISSION,03:31
2015-06-16,12:10 AM,Distort Light,Bend Sinister,Moxon- Daniel,"Stories Of Brothers, Tales Of Lovers",JIMMY BROWN,03:48

Both script would output

[akshay@localhost tmp]$ php test.php
Array
(
    [0] => Array
        (
            [date] => 2015-06-16
            [time] => 12:00 AM
            [label] => Island
            [artist] => U2
            [composer] => Clayton- Adam,The Edge,Bono,Mullen- Larry- Jr
            [album] => Songs Of Innocence
            [title] => SONG FOR SOMEONE
            [duration] => 03:46
        )

    [1] => Array
        (
            [date] => 2015-06-16
            [time] => 12:04 AM
            [label] => Lowden Proud
            [artist] => Fearing & White, Andy White, Stephen Fearing
            [composer] => White- Andy,Fearing- Stephen
            [album] => Tea And Confidences
            [title] => SECRET OF A LONG LASTING LOVE
            [duration] => 03:10
        )

    [2] => Array
        (
            [date] => 2015-06-16
            [time] => 12:07 AM
            [label] => Columbia
            [artist] => The Wallflowers
            [composer] => Dylan- Jakob,Irons- Jack,Mathis- Stuart,Richling- Greg,Jaffee- Rami
            [album] => Glad All Over
            [title] => REBOOT THE MISSION
            [duration] => 03:31
        )

    [3] => Array
        (
            [date] => 2015-06-16
            [time] => 12:10 AM
            [label] => Distort Light
            [artist] => Bend Sinister
            [composer] => Moxon- Daniel
            [album] => Stories Of Brothers, Tales Of Lovers
            [title] => JIMMY BROWN
            [duration] => 03:48
        )

)
Wednesday, September 21, 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 :
 
Share