mihavidakovic
mihavidakovic

Reputation: 15

Get values of nested array

I have this array:

$predmeti = [
        'slo' => [
            'ime' => 'Slovenščina',
            'ucitelj' => 'Ana Berčon',
            'nadimek' => '',
            'ucilnica' => '11'
        ],
        'mat' => [
            'ime' => 'Matematika',
            'ucitelj' => 'Nevenka Kunšič',
            'nadimek' => '',
            'ucilnica' => '12'
        ],
        'ang' => [
            'ime' => 'Angleščina',
            'ucitelj' => 'Alenka Rozman',
            'nadimek' => 'Rozi',
            'ucilnica' => '3'
        ]
];

How do I get each value for slo, mat, ang etc. with foreach loop? I just know how to get key and value in foreach, but not in this nested array.

Upvotes: 0

Views: 94

Answers (3)

AbraCadaver
AbraCadaver

Reputation: 78994

Why not just:

foreach($predmeti as $v) {
    echo $v['ime'];
    //etc...
}

or:

foreach($predmeti as $k => $v) {
    echo $k;
    echo $v['ime'];
    //etc...
}

Upvotes: 1

scrowler
scrowler

Reputation: 24405

I assume you're talking about the second level array, to get that you do another foreach inside:

foreach($predmeti as $key => $value) {
    foreach($value as $sub => $second) {
        echo $sub . ' -> ' . $second . PHP_EOL;
    }
}

Upvotes: 1

John Conde
John Conde

Reputation: 219834

Use foreach (array_expression as $key => $value) syntax:

foreach ($predmeti as $key => $value) {
    echo $key;
}

These values are the $key of each array inside of $predmeti.

From the manual:

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:

foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement

Upvotes: 0

Related Questions