【问题标题】:Convert string with array of json (PHP)用json数组转换字符串(PHP)
【发布时间】:2016-09-26 15:21:25
【问题描述】:

我将 JSON 数组作为字符串存储在 mysql 中

[{"id": 1, "mark": 5}, {"id": 2, "mark": 3}, {"id": 3, "mark": 2}]

当我尝试使用它时

@foreach ($places as $place)
   @foreach ($place->rates as $rate)

      {{var_dump($rate->marks)}}

   @endforeach
@endforeach

有问题。 $rate->marks 是一个字符串。我应该如何将其解码为数组?

UPD

当然我尝试使用 json_decode,但它返回错误

htmlentities() expects parameter 1 to be string, array given

已解决

我,笨蛋。问题不在 json_decode 中。我尝试使用需要字符串作为参数的 {{ }} 打印结果。

【问题讨论】:

  • 先解码json字符串,然后在foreach循环中使用。
  • 使用json_decode($rate->marks);
  • @splash58 当然我尝试使用 json_decode,但它返回错误 htmlentities() Expects parameter 1 to be string, array given

标签: php mysql json laravel


【解决方案1】:
<?php
$str = '[{"id": 1, "mark": 5}, {"id": 2, "mark": 3}, {"id": 3, "mark": 2}]';

$places = json_decode($str);

foreach ($places as $place) {
    echo 'id=>' . $place->id;
    echo 'mark=>' . $place->mark;
    echo "<br>";
}

【讨论】:

    【解决方案2】:

    您需要json_decode 您的标记,然后将它们作为数组进行迭代。像这样的东西(我不知道它是否适用于 Laravel,但你可以得到一个想法):

    @foreach ($places as $place)
       @foreach ($place->rates as $rate)
          @foreach (json_decode($rate->marks) as $mark)
            {{var_dump($mark->mark)}}
          @endforeach
       @endforeach
    @endforeach
    

    【讨论】:

      【解决方案3】:

      您的 json 中没有 rate,也没有 marks

      Check Online

      $json = '[{"id": 1, "mark": 5}, {"id": 2, "mark": 3}, {"id": 3, "mark": 2}]';
      $places = json_decode ($json);
      
      foreach ($places as $place)
            var_dump($place->mark);
      

      为 Laravel 设计代码,Online Debug 没有这个功能。

      告诉我。

      【讨论】:

        猜你喜欢
        • 2016-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多