Reputation: 1064
I am trying to get the array values using a foreach loop but getting Undefined index
error. This is the var_dump result shown below.
Array
(
[0] => Array
(
[0] => stdClass Object
(
[id] => 670
[snippets_name] => flkgjfldgkjlfdkj ldkjfg lkgfjd lkjg
[snippets_keyword] =>
[snippets_description] => dkjldkjflkfjldskfjldkfjlkjl
[snippet_image] => https://i.imgur.com/4WAnAP7.jpg
[snippet_tags] =>
[snippet_tags_id] =>
[seo_description] => Bootstrap example of
flkgjfldgkjlfdkj ldkjfg lkgfjd lkjg using
Bootstrap,Javascript,jquery,CSS code Snippet By hitesh-
chauhan57765
[snippets_html] => kfdlkjflkgjldkgjdlkgjdl l
[snippets_css] =>
[snippets_javascript] =>
[bootstrap_version_id] => 5
[javascript_version_id] => 1
[font_version_id] => 2
[url_slug] => flkgjfldgkjlfdkj-ldkjfg-lkgfjd-lkjg-
21588457
[snippets_created_ip] => 127.0.0.1
[snippets_category] => 0
[is_verified] => 0
[listed_by] => 28
[date_modified] => 2019-09-22 04:57:31
[date_created] => 2019-09-22 04:57:31
[is_featured] => 0
[search_values] =>
[counter_views] => 2
[avarage_rating] =>
[main_image] =>
[date_notify] =>
[status] => 0
[last_edit_ip] => 127.0.0.1
[date_notify_expired] =>
)
)
)
Here what I tried to get the results. But getting the Message: Undefined index: snippet_name error. please help.
foreach($snippets_tags as $post)
{
$listed_by = $post['snippets_name'];
}
Upvotes: 2
Views: 561
Reputation: 1064
I solved it using this code -
foreach ($snippets_tags as $snippets) {
foreach($snippets as $key=>$post)
{
$listed_by = $post->listed_by;
}
}
Upvotes: 0
Reputation: 6388
You can try
echo $snippets_tags[0][0]->snippets_name
Or , by using foreach
foreach($snippets_tags[0] as $post)
{
echo $post->snippets_name;echo '<br/>';
}
Working example : https://3v4l.org/D0aOi
Upvotes: 2
Reputation: 487
Dump shows that you have an arrays of objects (not arrays - that's why you're getting an "undefined index" message) nested in the outer array. So, to extract snippets_name
property of each object, you will need two foreach
cycles:
$snippetsNames = [];
foreach ($data as $objects) {
foreach ($objects as $object) {
$snippetsNames[] = $object->{'snippets_name'} ?? 'Unknown name';
}
}
Note that you can address object property by string, using curly braces syntax shown above. And you can also run into situation when there's no given property in the object; you should check that situation with isset()
(or just use the short and convenient syntax with ??
shown above).
Upvotes: 1