我有一个像这样的数组
Array
(
[0] => Array
(
[size] => 12" x 24"
[size_description] => <p>Rectified</p>
)
[1] => Array
(
[size] => 12" x 24"
[size_description] => <p>Rectified</p>
)
[2] => Array
(
[size] => 24" x 24"
[size_description] => <p>Rectified</p>
)
[3] => Array
(
[size] => 24" x 24"
[size_description] => <p>Rectified</p>
)
[4] => Array
(
[size] => 24" x 48"
[size_description] => <p>Rectified</p>
)
[5] => Array
(
[size] => 24" x 48"
[size_description] => <p>Rectified</p>
)
)
我想基于“ size”获得不同的子数组,并且我可以循环使用size和size_description。我试过array_unique不能正常工作,我只得到一个值,即size。我尝试过的是
$new_array = array_unique(array_map(function($elem){return $elem['size'];}, $size_array));
我想同时获得两个值。有什么办法吗?
答案 0 :(得分:2)
这将为您提供所需的结果
$newArr = array();
foreach($arr as $key => $value){
if(!in_array($value['size'], $newArr))
$newArr[$value['size']] = $value;
}
结果:-
Array
(
[12" x 24"] => Array
(
[size] => 12" x 24"
[size_description] => Rectified
)
[24" x 24"] => Array
(
[size] => 24" x 24"
[size_description] => Rectified
)
[24" x 48"] => Array
(
[size] => 24" x 48"
[size_description] => Rectified
)
)
答案 1 :(得分:2)
使用array_column()
使用size
分配新的关联键,而无需更改子数组的内容。这是通过null
参数完成的。
然后仅使用array_values()
代码:(Demo)
$array = [
['size' => '12" x 24"', 'size_description' => '<p>Rectified</p>'],
['size' => '12" x 24"', 'size_description' => '<p>Rectified</p>'],
['size' => '24" x 24"', 'size_description' => '<p>Rectified</p>'],
['size' => '24" x 24"', 'size_description' => '<p>Rectified</p>'],
['size' => '24" x 48"', 'size_description' => '<p>Rectified</p>'],
['size' => '24" x 48"', 'size_description' => '<p>Rectified</p>'],
];
var_export(array_values(array_column($array, null, 'size')));
阵列键不能重复-强制唯一。
答案 2 :(得分:1)
@Rakesh_jakhar提供的代码很酷,但是在php-array中按键访问速度更快,因为它存储为哈希表:
<?php
$size_array = [
...
];
$new_array = [];
foreach ($size_array as $item) {
if (!($size_array[$item['size']] ?? null)) {
$new_array[$item['size']] = $item;
}
}
$new_array = array_values($new_array);
var_dump($new_array);
,如果需要数字数组,请使用array_values