阵列排列

时间:2016-01-06 09:02:36

标签: php arrays loops object multidimensional-array

目前我的数组看起来像是:

array (size=3)
  0 => 
    object(stdClass)[32]
      public 'id' => string '11' (length=2)
      public 'housetype_id' => string '2' (length=1)
      public 'name' => string 'Test' (length=6)
      public 'excerpt' => string '' (length=0)
      public 'info_block_list_id' => string '1' (length=1)
  1 => 
    object(stdClass)[34]
      public 'id' => string '11' (length=2)
      public 'housetype_id' => string '2' (length=1)
      public 'name' => string 'Test' (length=6)
      public 'excerpt' => string '' (length=0)
      public 'info_block_list_id' => string '2' (length=1)
  2 => 
    object(stdClass)[35]
      public 'id' => string '11' (length=2)
      public 'housetype_id' => string '2' (length=1)
      public 'name' => string 'Test' (length=6)
      public 'excerpt' => string '' (length=0)
      public 'info_block_list_id' => string '3' (length=1)

由于只有info_block_list_id更改,我想重新排列我的数组:

object(stdClass)[35]
  public 'id' => string '11' (length=2)
  public 'housetype_id' => string '2' (length=1)
  public 'name' => string 'Test' (length=6)
  public 'excerpt' => string '' (length=0)
  public 'info_block_list_id' => 
    array (size=3)
       0 => string '1' (length=1)
       1 => string '2' (length=1)
       2 => string '3' (length=1)

2 个答案:

答案 0 :(得分:1)

如果你说每个对象与info_block_list_id属性的期望相同,你可以这么做。因此,将第一个对象保存到变量中,然后使用array_map()将所有info_block_list_id属性放入数组中,例如。

$object = $yourArray[0];
$object->info_block_list_id = array_map(function($v){
    return $v->info_block_list_id;
}, $yourArray);

答案 1 :(得分:0)

您希望创建一个包含唯一ID的哈希/键的变量,并将info_block_list_id属性更改为数组:

$items =  [];
foreach ($data as $item) {
    if (!isset($items[ $data->id ])) {
        $items[ $data->id ] = $item;
        $items[ $data->id ]->info_block_list_id = [];
    }
    $items[ $data->id ]->info_block_list_id[] = $item->info_block_list_id;
}

var_dump($items);