【问题标题】:Laravel collection sortby Illegal string offset 'detail'Laravel 集合 sortby 非法字符串偏移 'detail'
【发布时间】:2019-05-16 07:23:39
【问题描述】:

我需要排序方式详细名称“ASC”

我点击这个链接。https://laravel.com/docs/5.4/collections#method-sortby

这是我的调试数据

这是我的代码

$collection = collect($data);
dd($collection);
$sorted = $collection->sortBy(function ($product, $key) {
    return count($product['detail']);
});

$sorted->values()->all();

但显示错误“Illegal string offset 'detail'”

【问题讨论】:

    标签: php arrays laravel collections


    【解决方案1】:

    下次请将代码/dd 结果发布为文本而不是屏幕截图。谢谢!

    这里:

    $collection = collect($data);
    

    您的 $data 不是产品数组,而是 1 个产品(可能是产品属性的数组)。

    所以发生的事情是->sortBy(..) 迭代属性namedetail

    所以在第一次迭代中(您可以通过在sortBy 中执行dd($product) 来看到)$product 实际上是这样的:

    'Tour Guide Multilingual'
    

    关键是:

    'product'
    

    你得到错误是因为你试图访问一个字符串上的索引['detail'](因此“非法 string 偏移'detail'”)

    所以这是一个逻辑问题。我不确定您是如何获得 $data 或您的预期结果的,但您的 $data 中只有 1 个产品,所以真的没有什么可排序的

    【讨论】:

      【解决方案2】:

      试试这个..

      $collection = collect($data);
      $sorted = $collection->sortBy(function ($product, $key) {
          return $product['name'];
      });
      
      $sorted->values()->all();
      

      【讨论】:

      • 使用$product['name']而不是$product['detail'],如果你想在没有count()的名字的基础上排序
      • this dd($product) array:3 [▼ 0 => array:1 [▼ "detail" => "Speaking Guide - English" ] 1 => array:1 [▼ "detail" => "Audio - Thai" ] 2 => array:1 [▼ "detail" => "Audio - Chinese" ] ] 这是我的代码 $collection = collect($data); $sorted = $collection->sortBy(function ($product, $key) { dd($product); return $product['detail']; });
      • 在这种情况下使用return $product[0]['detail'];
      • 结果还是一样
      • 在使用 sortBy() 之前,您可以评论 dd()$collection 吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-30
      • 2020-11-29
      • 2017-09-13
      • 1970-01-01
      相关资源
      最近更新 更多