【问题标题】:Laravel array_forget() helper, for nested arraysLaravel array_forget() 助手,用于嵌套数组
【发布时间】:2019-04-17 16:31:19
【问题描述】:

我正在使用 Laravel,我有一个简单的嵌套数组

[
  ['id' => 1, 'name' => 'name1', 'phone' => '0'],
  ['id' => 2, 'name' => 'name2', 'phone' => '00'],
  ['id' => 3, 'name' => 'name3', 'phone' => '000']
]

我想使用 Laravel array_forget() 或任何其他简单的方法
在没有手机的情况下获得这个数组

【问题讨论】:

  • 不是stackoverflow.com/questions/369602/…的复制品吗?你真的需要使用 Laravel 吗?
  • 感谢@GabrielDevillers,但我的问题是关于嵌套数组,我尝试使用 Laravel 助手,它可以帮助我缩短代码

标签: php arrays laravel laravel-5


【解决方案1】:

您可以查看 laravel 的高级收集方法 - 一组方便的帮助程序,旨在处理 Laravel 中类似数组的集合。您可能需要的是except() method

【讨论】:

  • 在将我的集合转换为数组之前我尝试使用 except(),但我也失败了,因为我将它转换为一个简单的数组
【解决方案2】:

你可以这样做:

$elements = [
  ['id' => 1, 'name' => 'name1', 'phone' => '0'],
  ['id' => 2, 'name' => 'name2', 'phone' => '00'],
  ['id' => 3, 'name' => 'name3', 'phone' => '000']
];

$elements_without_phones = collect($elements)->map(function ($element){
    array_forget($element, 'phone');

    return $element;
});

【讨论】:

  • 感谢@HCK 每天帮助我,工作良好,但它不适用于关系键
  • @user9500574 对于这种情况,您可以使用API Resources。我刚刚在另一个问题中发布了答案,给它一个read。阅读我提到的第二种方法。
  • 我的数组实际上是从一个雄辩的集合转换而来的,我尝试了你的代码,但正如我所说,没有工作,为此,我将它转换为一个数组,然后我将它转换为数组和使用你的代码,不是很好,CONFUSION :)
  • @user9500574 如果您的数组来自 Eloquent 集合,请避免将其转换为数组并将 ->map() 链接到 eloquent 集合中:$elements = Model::where('field', 'value')->get()->map(...);
【解决方案3】:

您必须迭代数组数组,并在每个(子)数组上应用array_forget() 函数。

$array = [
    ['id' => 1, 'name' => 'name1', 'phone' => '0'],
    ['id' => 2, 'name' => 'name2', 'phone' => '00'],
    ['id' => 3, 'name' => 'name3', 'phone' => '000']
];

foreach($array as &$sub_array) { //note the passing by reference
    array_forget($sub_array, 'phone');
}

【讨论】:

    【解决方案4】:
    $collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);
    
    $filtered = $collection->only(['product_id', 'name']);
    
    $filtered->all();
    
    // Output: ['product_id' => 1, 'name' => 'Desk']
    

    【讨论】:

    • laravel 收集助手“仅”
    • 请添加一些上下文,甚至是简单的介绍,例如“您可以使用 Laravel Collection 等...”。另外,这个问题是关于嵌套数组的,所以你在这里没有完全回答这个问题。
    • 即 $result = collect( $array )->map( function ($item) { return collect( $item)->only( [ 'id', 'name' ]); } ) ->toArray();
    • 实际上在闭包内缺少toArray(),但这实际上回答了这个问题。请相应地编辑您的答案。
    • 你是对的。内部的toArray() 将是多余的。
    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    相关资源
    最近更新 更多