【问题标题】:php loop throught array and add to another arrayphp循环遍历数组并添加到另一个数组
【发布时间】:2018-04-07 20:06:58
【问题描述】:

我想要实现的是:

开放时间:

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

【问题讨论】:

    标签: php arrays laravel laravel-5


    【解决方案1】:

    在不知道原始数组的结构的情况下,我的第一个想法是尝试...

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-10
      • 2020-12-22
      • 2018-04-09
      • 1970-01-01
      • 1970-01-01
      • 2011-05-23
      • 2012-11-14
      • 2011-04-25
      相关资源
      最近更新 更多