mzcoxfde mzcoxfde - 2 months ago 6
PHP Question

Why does this say undefined offset 2 in a foreach loop

The

$snippet
variable has the following value:

Array
(
[0] => Array
(
[0] => Array
(
[id] => 1
[user_id] => 2
[title] => Title
[detail] => null
[lang_id] => 19
[edited] => false
[last_edited] =>
[created_date] => 2016-09-25 02:40:03
)

[1] => Array
(
[id] => 2
[user_id] => 2
[title] => Some other title
[detail] => null
[lang_id] => 19
[edited] => false
[last_edited] =>
[created_date] => 2016-09-25 02:40:03
)

[2] => Array
(
[id] => 3
[user_id] => 2
[title] => Huh!
[detail] => ...
[lang_id] => 19
[edited] => false
[last_edited] =>
[created_date] => 2016-09-25 03:04:48
)

)

[1] => Array
(
[0] => Array
(
[id] => 1
[user_id] => 2
[title] => Title
[detail] => null
[lang_id] => 19
[edited] => false
[last_edited] =>
[created_date] => 2016-09-25 02:40:03
)

[1] => Array
(
[id] => 2
[user_id] => 2
[title] => Some other title
[detail] => null
[lang_id] => 19
[edited] => false
[last_edited] =>
[created_date] => 2016-09-25 02:40:03
)

[2] => Array
(
[id] => 3
[user_id] => 2
[title] => Huh!
[detail] => ...
[lang_id] => 19
[edited] => false
[last_edited] =>
[created_date] => 2016-09-25 03:04:48
)

)

[2] => Array
(
[0] => Array
(
[id] => 4
[user_id] => 2
[title] => apache
[detail] => ...
[lang_id] => 1
[edited] => false
[last_edited] =>
[created_date] => 2016-09-25 03:05:06
)

)

)


I wanted my result to be something like:

Title
Some other title
Huh!
Title
Some other title
Huh!
apache


So I tried the following:

<?php foreach ($snippet as $key => $value): ?>
<?= $value[$key]['title'] ?>
<br />
<?php endforeach ?>


But the results were:

Title
Some other title

Notice: Undefined offset: 2


I can't figure out what I'm doing wrong.

Answer

Try this:

<?php 
     foreach ($snippet as $value):
        foreach($value as $title):
           echo $title['title']."<br>";
        endforeach;
      endforeach; 
 ?>