2

I am trying to combine different index into one index.Given code is sample..

Array(
[0] => stdClass Object
    (
        [player_id] => 92
        [player_name] => XYZ
    )

[1] => stdClass Object
    (
        [player_type_id] => 4
        [type] => All-Rounder
    ))

expected answer would be

Array([0] => stdClass Object
     ( 
      [player_id] => 92
      [player_name] => XYZ
      [player_type_id] => 4
      [type] => All-Rounder
     )
Chetan Ameta
  • 7,696
  • 3
  • 29
  • 44
hmamun
  • 154
  • 1
  • 15

3 Answers3

0

Try this :

$obj_merged = (object) array_merge((array) $obj1, (array) $obj2);

Monty
  • 1,110
  • 7
  • 15
0

Please try this :

$objArr1 =  (array)$yourArr[0];
$objArr2 =  (array)$yourArr[1];

$mergedArr = (object)array_merge($objArr1,$objArr2);
dhi_m
  • 1,235
  • 12
  • 21
0

You can achive in 2 way.

1) Using array_merge function

2) Using + operator

Refer below example:

$obj1 = new StdClass();
$obj1->player_id = 92;
$obj1->player_name = 'Test Name';


$obj2 = new StdClass();
$obj2->player_type_id = 92;
$obj2->type = 'Test Name';

$array = array($obj1, $obj2);

$merged_array = (object) ((array) $obj1 + (array) $obj2);

print_r($merged_array);

echo '--------------------------------------- <br />';
$obj_merged = (object) array_merge((array) $obj1, (array) $obj2);

print_r($obj_merged);

Output:

stdClass Object
(
    [player_id] => 92
    [player_name] => Test Name
    [player_type_id] => 92
    [type] => Test Name
)
--------------------------------------- 
stdClass Object
(
    [player_id] => 92
    [player_name] => Test Name
    [player_type_id] => 92
    [type] => Test Name
)

One more method using foreach loop:

foreach($obj2 as $k => $v){
  $obj1->$k = $v;
}

print_r($obj1);

Output:

stdClass Object
(
    [player_id] => 92
    [player_name] => Test Name
    [player_type_id] => 92
    [type] => Test Name
)
Chetan Ameta
  • 7,696
  • 3
  • 29
  • 44