Z
Z
ZaxapKramer2016-06-01 19:03:56
PHP
ZaxapKramer, 2016-06-01 19:03:56

Is it possible to get data from an array in a shorter way?

There is an array like:

$array = [
    'I' => [
        'can' => [
            'fly'   => ['alone', 'too', 'with you'],
            'eat'   => ['rise', 'soup', 'your cooking'],
            'dream' => ['alone', 'of you', 'again']
        ],
        'love' => [
            'you'  => ['so much', ':)', 'too']
        ]
    ]
];

I receive offers like this:
foreach ($array as $actor => $verbs) {
    foreach ($verbs as $verb => $actions) {
        foreach ($actions as $action => $words) {
            foreach ($words as $word) {
                echo $actor , ' ' , $verb , ' ' , $action , ' ' , $word , '<br>';
            }
        }
    }
}

// I can fly alone
// I can fly too
// I can fly with you
// ...
// I love you too

Verbs like this:
foreach ($array as $actor => $verbs) {
    foreach ($verbs as $verb => $key) {
        echo $verb , '<br>';
    }
}

// can
// love

I struggled with this for a long time.
To be honest, I don’t understand very clearly (I read the docs, looked at examples, I don’t have enough practice, I think) exactly how arrays work ( I almost never came across $key => $value ).
In my practice, there were practically no arrays, except for the configuration file with database data, but here the array ... a little more - causes difficulties))
For some reason it seems to me that the data given above (especially verbs) can be obtained in a wrong way abstrusely. Correct me if I'm wrong. Thanks in advance :)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2016-06-01
@ZaxapKramer

Everything is fine, as an option, you can write through
php.net/array_map
or
php.net/manual/ru/function.array-walk.php
But in this case, it probably makes no sense.

N
novrm, 2016-06-01
@novrm

IteratorIterator

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question