Rzj Hayabusa
Rzj Hayabusa

Reputation: 657

How to merge two arrays of objects in Laravel controller?

I have these function to call to sets of data which is using DB query for Data A and CURL for Data B.

Right now I managed to display the output but somehow Data A cannot merge into Data B. My code as below.

Namespace :

use \stdClass;

Code :

public function find($user = null) {
    if($user)
    {
        // Data A
        $sql            = "SELECT * FROM TABLE WHERE ID = '".$user."' "; 
        $arr            = DB::connection('mysql')->select($sql);
        $resultData     = new \stdClass();

        foreach ($arr as $key => $value) 
        {
            $resultData->$key = $value; // Extract Data A table
        }


        // Data B
        $url    = "http://localhost/data/curl.php?value=".$user; 
        $ch     = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL,$url);
        $result = curl_exec($ch);
        curl_close($ch);
        $row    = json_decode($result, true); 

        foreach ($row as $key => $value) 
        {
            $resultData->$key = $value; // Extract Data B 
        }  

        dd($resultData);
        return true;
    }
    return false;
}

My goal is to merge these two sets of data (A & B) into one.

What I get right now is like this in my browser if I display output separately. When I combined it, it only show Data B :

Data A

{#310 
  +"0": {#213 
    +"id": "1"
    +"name": "MIKE"
    +"acc_no": "AAA001"
    +"email": "[email protected]" 
  }
}

Data B

{#310 
  +"0": "CLERK"
  +"TITLE": "CLERK"
  +"1": "Clerk, IT Department"
  +"POSITION": "Clerk, IT Department"
  +"2": "Rozaimi Bin Zamahri"
  +"SECTION": "Office"
}

Appreciate if someone can help me. Thanks.

Upvotes: 0

Views: 2574

Answers (2)

TsaiKoga
TsaiKoga

Reputation: 13394

Problem1: Don't just concat sql string with the params, it has SQL-injection problem, if you want to use DB::select with params, you can do it like this:

$sql  = "SELECT * FROM TABLE WHERE ID = ? "; 
$arr  = DB::connection('mysql')->select($sql, [$user]);

Problem2: Because you are using DB select method, it will return an array nest with objects. you need to get the object first, do something like this:

$arr = DB::connection('mysql')->select($sql)[0];

And then you can merge them by loop or just turn them to array and merge them.

Upvotes: 2

Paras Raiyani
Paras Raiyani

Reputation: 768

Try this:-

    $data1=(object)['a','b'];
    $data2=(object)['c','d'];
    $result = (object) array_merge(
        (array) $data1, (array) $data2);

    print_r($result);

Upvotes: 0

Related Questions