如何使用foreach循环获取数组值

时间:2019-09-22 06:17:28

标签: php arrays foreach

我正在尝试使用foreach循环获取数组值,但遇到Undefined index错误。这是下面显示的var_dump结果。

       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] => 
            )

             )

        )

这是我尝试获得结果的方法。但是得到消息:未定义索引:snippet_name错误。请帮忙。

                foreach($snippets_tags as $post)

                { 
               $listed_by = $post['snippets_name'];
                }

4 个答案:

答案 0 :(得分:2)

您可以尝试

echo $snippets_tags[0][0]->snippets_name

或者,通过使用foreach

foreach($snippets_tags[0] as $post)
{ 
  echo $post->snippets_name;echo '<br/>';
}

工作示例:https://3v4l.org/D0aOi

答案 1 :(得分:1)

转储显示您有一个嵌套在外部数组中的对象数组(不是数组-这就是为什么您收到“未定义索引”消息的原因)。因此,要提取每个对象的snippets_name属性,您将需要两个foreach周期:

$snippetsNames = [];
foreach ($data as $objects) {
    foreach ($objects as $object) {
       $snippetsNames[] = $object->{'snippets_name'} ?? 'Unknown name';
    }
}

请注意,您可以使用上面显示的花括号语法按字符串处理对象属性。当对象中没有给定的属性时,您也可能会遇到这种情况。您应该使用isset()检查这种情况(或仅使用上面显示的??的简短语法)。

答案 2 :(得分:0)

我使用此代码解决了它-

foreach ($snippets_tags as $snippets) {

                foreach($snippets as $key=>$post)

                { 
                    $listed_by = $post->listed_by;
                }
         }

答案 3 :(得分:-1)

您可以尝试

$Data = $snippets_tags[0];
$ret_arr = {};
foreach($Data as $post)
{ 
  $ret_arr['Name'] = $post['snippets_name'];
}