如何从数组中提取每一项? laravel/php

How to extract each of the items from an array? laravel/php

我在数组中有 50 个项目,看起来像这样:

     array:50 [▼
      0 => {#253 ▼
        +"message": "message_1"
        +"created_time": {#254 ▼
          +"date": "2016-03-03 07:54:05.000000"
          +"timezone_type": 1
          +"timezone": "+00:00"
        }
        +"id": "167633226631991_1051771021551536"
      }
      1 => {#255 ▼
        +"message": "message_2"
        +"created_time": {#256 ▼
          +"date": "2016-03-02 13:35:26.000000"
          +"timezone_type": 1
          +"timezone": "+00:00"
        }
        +"id": "167633226631991_1051313571597281"
      }
    ]

我需要获取数组中的每个变量。但我不断收到一条错误消息:

Undefined property: stdClass::$message

我不确定我错过了什么我试过:

     foreach ($posts as $post) {
            $test = array('message' => $post->message );
     }

还有

$a = -1;

$alpha = 0;

$omega = count($posts);

$empty_array = array();

foreach (range($alpha,$omega) as $i) {
  ++$a;
  $test = $posts[$a]->message;
  array_push($empty_array, $test);
  }

但我遇到了同样的错误。我正在使用 laravel 5.2。

更新: 该数组来自 facebook 的图表 API。我正在使用以下方法转换 json 格式:

$posts = json_decode($userNode['posts']);

这样做会显示 array:50 如上。

由于该数组是一个对象数组,因此您在键入 $post->message 时就正确地引用了它。做 $post['message'] 是行不通的,因为它不是数组的数组。

我认为会出现 Undefined property: stdClass::$message 错误,因为您的 $posts 数组中的某些对象具有空的 +message 或不存在的 +message

处理此问题的最佳方法是使用 isset()。但是,您还需要将 $test 更改为 $test[] 以防止它在每次循环时被覆盖。

代码:

    foreach ($posts as $post) {
        isset($post->message) ? $test[] = array('message' => $post->message ) : null;
    }

之后,dd($test)会为您提供一个包含消息的数组

如果你真的只是想要一个简单的消息数组,那么这样做:

    foreach ($posts as $post) {
        isset($post->message) ? $test[] = $post->message : null;
    }