Search code examples
phparrayslaraveljoin

How to join a array and MySQL table in Laravel


i have an array like

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 [▶]
] 

from a session variable this array and mysql table fields are id,name,img etc.. how to join the array.product_id and table.id ,

my query like $table=DB::select('SELECT * FROM products');i am doing in laravel any way to join mysql table and array?


Solution

  • Your mysql dump which you want to join is missing. But i think i understand you want:

    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])
        }
    
    }