我想从不同的数组中获取最大值。基本上,阵列来自3个不同的网站,我需要知道每个产品的最大tags
和photos
值。
我有以下数组:
$data = array(
'domain1.com' => array(
'id1' => array(
'tags' => '5',
'photos' => '4',
),
'id2' => array(
'tags' => '8',
'photos' => '2',
),
'id3' => array(
'tags' => '6',
'photos' => '1',
),
),
'domain2.com' => array(
'id1' => array(
'tags' => '3',
'photos' => '1',
),
'id2' => array(
'tags' => '4',
'photos' => '9',
),
'id3' => array(
'tags' => '2',
'photos' => '0',
),
),
'domain3.com' => array(
'id1' => array(
'tags' => '7',
'photos' => '3',
),
'id2' => array(
'tags' => '9',
'photos' => '5',
),
'id3' => array(
'tags' => '2',
'photos' => '4',
),
),
);
我需要获得以下结果:
$data = array(
'id1' => array(
'tags' => '7',
'photos' => '4',
),
'id2' => array(
'tags' => '9',
'photos' => '9',
),
'id3' => array(
'tags' => '6',
'photos' => '4',
),
);
答案 0 :(得分:0)
最简单的方法是使用嵌套的foreach循环来迭代和捕获数据。如果在结果数组中找到更高的值,则结果会更新。
$results = [];
foreach ($data as $domain => $items) {
foreach ($items as $id => $elements) {
if (!isset($results[ $id ])) {
$results[ $id ] = [];
}
foreach ($elements as $tag => $value) {
if (!isset($results[ $id ][ $tag ]) || $value>$results[ $id ][ $tag ]) {
$results[ $id ][ $tag ] = $value;
}
}
}
}
print_r($results);
答案 1 :(得分:0)
这可以通过简单的循环解决:
$new = array();
foreach($data as $domain){
foreach($domain as $id => $_data){
foreach($_data as $elem => $value) {
if(!isset($new[$id][$elem]) || $value > $new[$id][$elem]){
$new[$id][$elem] = $value;
}
}
}
}
返回:
Array
(
[id1] => Array
(
[tags] => 7
[photos] => 4
)
[id2] => Array
(
[tags] => 9
[photos] => 9
)
[id3] => Array
(
[tags] => 6
[photos] => 4
)
)