是否可以使用不同的键获得相同的对象?

时间:2016-05-06 19:26:06

标签: php laravel

我想转换对象中的所有name_t

object:4 [▼
  0 => {#161 ▼
    +"id": 1
    +"name_t": "coffee"
  }
  1 => {#194 ▼
    +"id": 2
    +"name_t": "Tea"
  }
  2 => {#195 ▼
    +"id": 3
    +"name_t": "Chocolate"
  }
  3 => {#196 ▼
    +"id": 4
    +"name_t": "To chocklate"
  }
]

name_c s,就像在这个对象中一样:

object:4 [▼
  0 => {#161 ▼
    +"id": 1
    +"name_c": "coffee"
  }
  1 => {#194 ▼
    +"id": 2
    +"name_c": "Tea"
  }
  2 => {#195 ▼
    +"id": 3
    +"name_c": "Chocolate"
  }
  3 => {#196 ▼
    +"id": 4
    +"name_c": "To chocklate"
  }
]

我已经尝试过这个功能了:

 public function prepareToFilter($objects)
        {
        $temp = 0;
        foreach($objects as $object)
        {

            $prepared[$temp] = ['id' => $object->id, 'name_c' => $object->name_t];
            $temp++;
        }
        return $prepared;
    } 

..但它给了我一个数组,而不是一个对象。

2 个答案:

答案 0 :(得分:2)

使用array_map函数,并将值转换为对象:

public function prepareToFilter($data)
{
    return array_map(function ($item) {
        return (object) [
            'id'     => $item->id,
            'name_c' => $item->name_t,
        ];
    }, $data);
}

答案 1 :(得分:1)

尝试=>

    foreach($objects as $object)
    {
        $object->name_c = $object->name_t;
        unset($object->name_t);
    }