Codeigniter将项目插入数组

时间:2017-03-08 06:51:01

标签: php arrays codeigniter

嗨我有阵列,它看起来像这样:

array (size=2)
  0 => 
    object(stdClass)[21]
      public 'id' => string '1' (length=1)
      public 'name' => string 'John' (length=4)
  1 => 
    object(stdClass)[22]
      public 'id' => string '12' (length=2)
      public 'name' => string 'Mary' (length=4)

现在,对于每个ID,我将它们传递给另一个查询以从另一个表中获取另一个信息,如何为每个ID添加结果查询以添加到数组中,如下所示:

array (size=2)
  0 => 
    object(stdClass)[21]
      public 'id' => string '1' (length=1)
      public 'name' => string 'John' (length=4)
      public 'OfficeName' => string 'Records' (length=7)
  1 => 
    object(stdClass)[22]
      public 'id' => string '12' (length=2)
      public 'name' => string 'Mary' (length=4)
      public 'OfficeName' => string 'Accounting' (length=10)

2 个答案:

答案 0 :(得分:0)

一旦你拥有了$ OfficeName,你就需要像这样做一个foreach循环:

foreach ($array as $k) {
    $k->OfficeName = $OfficeName;
}

答案 1 :(得分:0)

First Array

$ar = array(
        (object)array(
                'id' => '1',
                'name' => 'John'
            ),
        (object)array(
                'id' => '12',
                'name' => 'Mary'
            )
    );


据说你要查询获取办公室名称并假设查询结果如下:

结果数组

$ar2 = array(
        (object)array(
                'id' => '1',
                'OfficeName' => 'Records'
            ),
        (object)array(
                'id' => '12',
                'OfficeName' => 'Accounting'
            )
    );


要将第二个数组中的值插入第一个数组,我会做这样的事情:

$new_arr = array();
    foreach ($ar as $value) {

        foreach ($ar2 as $row) {
            if ($row->id == $value->id) {
                $temp_ar = (object)array(
                    'id' => $value->id,
                    'name' => $value->name,
                    'OfficeName' => $row->OfficeName
                );
                array_push($new_arr, $temp_ar);
            }
        }            
    }


$ new_arr将结果数组的内容与第一个数组一起使用。