php循环通过数组并添加到另一个数组

时间:2017-10-26 12:28:30

标签: php arrays laravel laravel-5

我想要实现的目标是:

opening_times:

0:
1:
2:

我实际拥有的是:

{
  "message": {
    "entity": {
      "google_places": [
        {
          "opening_times": [
            "Monday: 11:30 AM – 8:30 PM"
          ]
        },
        {
          "opening_times": [
            "Tuesday: 11:30 AM – 8:30 PM"
          ]
        },
        {
          "time": "3 weeks ago",
          "author_name": "Adam Walsh",
          "rating": 4
        }
      ]
    }
  }
}

我的代码是:

if (!empty($dirty_googlePlaces_array['result']['opening_hours']['weekday_text'])) {
    foreach ($dirty_googlePlaces_array['result']['opening_hours']['weekday_text'] as $opening) {
        $googlePlaces_array[] = ['opening_times' => [ $opening]];
    }
}
if (!empty($dirty_googlePlaces_array['result']['reviews'])) {
    foreach ($dirty_googlePlaces_array['result']['reviews'] as $review) {
        $author_name = $review['author_name'];
        $time = $review['relative_time_description'];
        $rating = $review['rating'];
    }
}
$googlePlaces_array[] = [
        'time' => $time,
        'author_name' => $author_name,
        'rating' => $rating,
    ];
return response()->json(['message' => ['entity' => [
                                                            'google_places' => $googlePlaces_array
]]], 200);

如何重新构造该格式以获得数组:

googlePlaces:
  opening_times:
   array here
  time:time
  author_name:string
  rating: number

1 个答案:

答案 0 :(得分:0)

在不知道原始数组的结构的情况下,我首先想到的是尝试......

foreach ($dirty_googlePlaces_array['result']['opening_hours']['weekday_text'] as $key => $opening) {
    $googlePlaces_array['opening_times'][$key] = $opening;
}

请注意foreach中的$key => $opening以及$opening值的分配结构