如果您想:
- 检查进入 array_merge 的每个参数实际上是一个数组
- 指定要合并的数组之一中的特定属性
您可以使用此功能:
function mergeArrayofArrays($array, $property = null)
{
return array_reduce(
(array) $array, // make sure this is an array too, or array_reduce is mad.
function($carry, $item) use ($property) {
$mergeOnProperty = (!$property) ?
$item :
(is_array($item) ? $item[$property] : $item->$property);
return is_array($mergeOnProperty)
? array_merge($carry, $mergeOnProperty)
: $carry;
}, array()); // start the carry with empty array
}
让我们看看它的实际效果。这里有一些数据:
简单结构:要合并的纯数组。
$peopleByTypesSimple = [
'teachers' => [
0 => (object) ['name' => 'Ms. Jo', 'hair_color' => 'brown'],
1 => (object) ['name' => 'Mr. Bob', 'hair_color' => 'red'],
],
'students' => [
0 => (object) ['name' => 'Joey', 'hair_color' => 'blonde'],
1 => (object) ['name' => 'Anna', 'hair_color' => 'Strawberry Blonde'],
],
'parents' => [
0 => (object) ['name' => 'Mr. Howard', 'hair_color' => 'black'],
1 => (object) ['name' => 'Ms. Wendle', 'hair_color' => 'Auburn'],
],
];
不太简单:数组数组,但想指定人员并忽略计数。
$peopleByTypes = [
'teachers' => [
'count' => 2,
'people' => [
0 => (object) ['name' => 'Ms. Jo', 'hair_color' => 'brown'],
1 => (object) ['name' => 'Mr. Bob', 'hair_color' => 'red'],
]
],
'students' => [
'count' => 2,
'people' => [
0 => (object) ['name' => 'Joey', 'hair_color' => 'blonde'],
1 => (object) ['name' => 'Anna', 'hair_color' => 'Strawberry Blonde'],
]
],
'parents' => [
'count' => 2,
'people' => [
0 => (object) ['name' => 'Mr. Howard', 'hair_color' => 'black'],
1 => (object) ['name' => 'Ms. Wendle', 'hair_color' => 'Auburn'],
]
],
];
运行
$peopleSimple = mergeArrayofArrays($peopleByTypesSimple);
$people = mergeArrayofArrays($peopleByTypes, 'people');
结果 - 两者都返回:
Array
(
[0] => stdClass Object
(
[name] => Ms. Jo
[hair_color] => brown
)
[1] => stdClass Object
(
[name] => Mr. Bob
[hair_color] => red
)
[2] => stdClass Object
(
[name] => Joey
[hair_color] => blonde
)
[3] => stdClass Object
(
[name] => Anna
[hair_color] => Strawberry Blonde
)
[4] => stdClass Object
(
[name] => Mr. Howard
[hair_color] => black
)
[5] => stdClass Object
(
[name] => Ms. Wendle
[hair_color] => Auburn
)
)
额外的乐趣:如果你想在一个数组或对象中挑出一个属性,比如从人员对象数组(或关联数组)中挑选出一个属性,你可以使用这个函数
function getSinglePropFromCollection($propName, $collection, $getter = true)
{
return (empty($collection)) ? [] : array_map(function($item) use ($propName) {
return is_array($item)
? $item[$propName]
: ($getter)
? $item->{'get' . ucwords($propName)}()
: $item->{$propName}
}, $collection);
}
getter 用于可能受保护/私有的对象。
$namesOnly = getSinglePropFromCollection('name', $peopleResults, false);
返回
Array
(
[0] => Ms. Jo
[1] => Mr. Bob
[2] => Joey
[3] => Anna
[4] => Mr. Howard
[5] => Ms. Wendle
)