【问题标题】:Cannot use object of type Illuminate\\Http\\JsonResponse as array in Laravel不能在 Laravel 中使用 Illuminate\\Http\\JsonResponse 类型的对象作为数组
【发布时间】:2020-06-26 06:48:06
【问题描述】:

我有这样的数据集:

$data[] =
Array
(
    [u_d] => ABCDEF
    [0] => Array
        (
        [one] => oned
        [two] => 222
        [three] => three
        [four] => 444
        [five] => 555
        [events] => Array
            (
                [0] => Array
                    (
                        [feed] => Array
                            (
                                [0] => Array
                                    (
                                        [date-time] => 191018080000
                                        [sub-type] => abc
                                        [comments] => test comments
                                        [parameter-list] => para1, para2
                                        [state] => bad
                                        [value] => 1000
                                    )

                            )

                    )

            )
        )


    [1] => Array
        (
            [one] => two
            [two] => 224562
            [three] => thyyree
            [four] => 445344
            [five] => 5345355
            [events] => Array
                (
                )

        )
)

我只需要获取事件并删除空事件。但是首先我尝试获取类似这样的事件,但它给出了一个错误。

                               $new = [];
                                 for($i=0 ; $i < count($data)-1 ; $i++)
                                {
                                  if(count($data[$i]['events']) > 0)
                                  {
                                    
                                    $new[] = $data[$i]['events'];
                                   
                                  }
                                  
                                }
                                print_r ($new);

但它给了我一个错误:不能使用 Illuminate\Http\JsonResponse 类型的对象作为数组

谁能帮我解决这个问题?

谢谢

【问题讨论】:

  • json_decode($data) 首先你需要先解码json。之后你可以用 php 的方式访问它们的值。
  • 嗨,我试图解码 json,它给了我消息":"json_decode() 期望参数 1 是字符串,给定数组" ...我也尝试从字符串转换为数组这 $data = array($data); 但不工作
  • 请提供带有行号的完整错误消息。还要在您的问题中指定行。
  • 试试这样$data[$i]-&gt;events
  • 我尝试了 $data[$i]->events,它给了我这样的错误:尝试获取非对象的属性","status_code":

标签: php arrays laravel error-handling


【解决方案1】:

您需要解码 $data[0] 而不是 $data,因为您正在这样做

$data[] =

同样的for循环,你应该这样做

if(count($data[0][$i]['events']) > 0)

【讨论】:

    【解决方案2】:

    你可以像这样使用 Laravel collect() 方法:

    collect($your_array)->toJson();
    

    https://laravel.com/docs/7.x/collections

    【讨论】:

    • 嗨,我尝试使用 collect 转换为 Json,但是,我收到了一个空白数组。你知道为什么会这样吗?
    猜你喜欢
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 2019-12-09
    • 2019-12-11
    相关资源
    最近更新 更多