首页 > 解决方案 > 如何在 Laravel 中加入数组和 MySQL 表

问题描述

我有一个像

array:5 [▼
  188 => array:17 [▼
    "user_id" => "176"
    "product_id" => "188"
    "qty" => "2"
    "date" => "03-05-2020"
    "product_type" => "rear type"
    "custom_color_title" => ""
    "custom_color_price" => ""
    "bolt_title" => ""
    "bolt_price" => ""
    "hub_center_rings_title" => ""
    "hub_center_rings_price" => ""
    "wheel_spacers_title" => ""
    "wheel_spacers_price" => ""
    "tire_pressure_title" => ""
    "tire_pressure_price" => ""
    "product_price" => 1890
    "product_size" => ""
  ]
  176 => array:17 [▼
    "user_id" => ""
    "product_id" => "176"
    "qty" => "2"
    "date" => "03-05-2020"
    "product_type" => "wheel type"
    "custom_color_title" => ""
    "custom_color_price" => ""
    "bolt_title" => ""
    "bolt_price" => ""
    "hub_center_rings_title" => ""
    "hub_center_rings_price" => ""
    "wheel_spacers_title" => ""
    "wheel_spacers_price" => ""
    "tire_pressure_title" => ""
    "tire_pressure_price" => ""
    "product_price" => 1680
    "product_size" => ""
  ]
  224 => array:17 [▶]
] 

从会话变量这个数组和 mysql 表字段是 id、name、img 等。如何加入 array.product_id 和 table.id ,

我的查询就像$table=DB::select('SELECT * FROM products');我在 laravel 中所做的那样以任何方式加入 mysql 表和数组?

标签: arrayslaraveljoin

解决方案


您要加入的 mysql 转储丢失。但我想我明白你想要:

foreach($sessionArray as $sessionArrayKey => $sessionArrayVal)
{
    $findInDb = array_search($sessionArrayVal['product_id'], array_column($dbArray, 'id'));

    if ($findInDb)
    {
        $sessionArray[$sessionArrayKey] = array_merge($sessionArray[$sessionArrayKey],$dbArray[$findInDb])
    }

}

推荐阅读