首页 > 解决方案 > 如何将结果值映射到laravel中的键值?

问题描述

我有 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
]

标签: phparrayslaravelcombinationsarray-map

解决方案


在传递 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];
        }

推荐阅读