如何将不同的索引合并为一个索引

时间:2016-02-18 06:49:52

标签: php arrays arrayobject

我正在尝试将不同的索引合并到一个索引中。给出的代码是示例..

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

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

预期答案将是

Array([0] => stdClass Object
     ( 
      [player_id] => 92
      [player_name] => XYZ
      [player_type_id] => 4
      [type] => All-Rounder
     )

3 个答案:

答案 0 :(得分:0)

试试这个:

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

答案 1 :(得分:0)

请试试这个:

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

$mergedArr = (object)array_merge($objArr1,$objArr2);

答案 2 :(得分:0)

你可以用2种方式实现。

1)使用from datetime import date, datetime, timedelta import pandas_datareader.data as web todays_date = date.today() n = 30 date_n_days_ago = date.today() - timedelta(days=n) yahoo_data = web.DataReader('ACC.NS', 'yahoo', date_n_days_ago, todays_date) yahoo_data_20_day = yahoo_data.tail(20) 功能

2)使用array_merge运算符

参考下面的例子:

+

<强>输出:

$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);

使用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 ) 循环的另一种方法:

foreach

<强>输出:

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

print_r($obj1);