【问题标题】:Laravel 5.3 : issues in json structure after removing an item from an array [duplicate]Laravel 5.3:从数组中删除项目后json结构中的问题[重复]
【发布时间】:2017-06-03 00:20:04
【问题描述】:

我有一个这样的数组

Array
(
    [0] => Array
        (
            [title] => first 
            [description] => first item
        )

    [1] => Array
        (
            [title] => second 
            [description] => second item
        )

)

并使用集合forget() 方法从数组中删除一个项目

$new = collect($arr);
$new->forget(0);
echo json_encode($new->all());

这是上面的json输出

{"1":{"title":"second ","description":"second item"}}

但我期待这样的 json

[{"title":"second ","description":"second item"}]

另外,在应用forget() 方法后如何重新索引上述数组??

【问题讨论】:

    标签: php json laravel-5


    【解决方案1】:

    开始数组

    Array
    (
        [0] => Array
            (
                [title] => first 
                [description] => first item
            )
    
        [1] => Array
            (
                [title] => second 
                [description] => second item
            )
    
    )
    

    你删除数组的第一个元素:

    Array
    (
        [1] => Array
            (
                [title] => second 
                [description] => second item
            )
    
    )
    

    json_encode 在这个数组上,返回这个:
    {"1":{"title":"second ","description":"second item"}}

    所以你的输出是正确的。

    你需要在这个数组上运行json_encode,以获得你想要的输出:

    Array
    (
        [title] => second 
        [description] => second item
    )
    

    例如,您可以为此使用 array_shift 函数:

    $new = collect($arr);
    $new->forget(0);
    echo json_encode(array_shift($new->all()));
    

    另一个例子是array_values 函数,以防您需要多个数组:

    $new = collect($arr);
    $new->forget(0);
    echo json_encode(array_values($new->all()));
    

    【讨论】:

      猜你喜欢
      • 2021-08-01
      • 1970-01-01
      • 2016-01-05
      • 2022-06-10
      • 1970-01-01
      • 2012-11-21
      • 1970-01-01
      • 2021-09-07
      • 2016-11-24
      相关资源
      最近更新 更多