【问题标题】:how to map result value to its key value in laravel?如何将结果值映射到laravel中的键值?
【发布时间】:2020-12-30 15:22:54
【问题描述】:

我有 2 个数组,第一个是数据,第二个是结果数组

我正在尝试用数据数组映射结果数组 所以我使用了 combine() 方法

但问题是,如果我有相同的结果,那么它会映射 1 个项目并跳过剩余的考虑

第一个数组($customersidurl)

[
    19 => null,
    20 => null,
    21 => null,
    24 => "31.4346084,74.2793016,12",
    25 => null,
    26 => "31.58834,74.37375"
]

第二个结果数组($shortest)

[
    0 => 8532.8587780495,
    1 => 8532.8587780495,
    2 => 8532.8587780495,
    3 => 18.831126689097,
    4 => 8532.8587780495,
    5 => 0.85071506409078
]

我的输出

[
    "" => 8532.8587780495,
    31.4346084,74.2793016,12 => 18.831126689097,
    31.58834,74.37375 => 0.85071506409078,
]

它跳过了 3 个结果。我不希望这种跳过发生。我使用的代码是

$customersidurl = Customer::whereIn('created_by', $adminot)
    ->get()
    ->pluck('location_url', 'id');

foreach ($customersidurl as $short) {
    $shortest[] = $this->getsortedDistance($cords , $cords1 ,$short);
}

$combined = $customersidurl->combine($shortest);

有人可以帮助我任何其他可以将每个元素映射到相应的元素吗?

需要的输出是

[
    "" => 8532.8587780495,
    "" => 8532.8587780495,
    "" => 8532.8587780495,
    31.4346084,74.2793016,12 => 18.831126689097,
    "" => 8532.8587780495,
    31.58834,74.37375 => 0.85071506409078
]

【问题讨论】:

  • 能否请您提供您想要的输出,因为目前尚不清楚?
  • @dazed-and-confusedthanx 感谢您的贡献,我已经更新了问题
  • 欢迎来到。由于您的第一个结果中有 3 个空值,因此结果中有一个对应的项目是正常的。一个数组中不能有 2 个相同的键。
  • 关于你刚刚结束的问题:collect($a)->mapWithKeys(fn($i) => [explode(' => ', $i)[0] => explode(' => ', $i)[1]])->all() 应该会给你你想要的结果。此外,您所需的输出显示 "" 重复作为键。一个数组不能有两个相同的键。

标签: php arrays laravel combinations array-map


【解决方案1】:

在传递 id 时试试这个

$customersidurl = Customer::whereIn('created_by', $adminot)->get()->pluck('location_url', 'id');
      
        foreach ($customersidurl as $short){
         $shortest[] = $this->getsortedDistance($cords , $cords1 ,$short);
        }
        $customersid = Customer::whereIn('created_by', $adminot)->pluck('id')->toArray();
        for($i = 0; $i < sizeof($customersid); $i++){
            $maping[$customersid[$i]] =  $shortest[$i];
        }

【讨论】:

    猜你喜欢
    • 2021-03-05
    • 2018-12-21
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多