我有以下数组:
Array
(
[0] => Array
(
[location] => Central>Europe>Italy
[Total_S] => 4
[Total_R] => 0
)
)
Array
(
[1] => Array
(
[location] => Central>Europe>Spain
[Total_S] => 4
[Total_R] => 0
)
)
数组中有超过100个。
是否可以根据位置在数组内搜索,例如,如果location
包含' Central>Europe',我想要sum Total_S
在MySQL中可以使用LIKE
: LIKE '%Central>Europe%'
我不知道PHP是否有相同的功能在这样的数组中做到这一点
利用PHP 5.5中新增的array_column()函数:
$data = array(
array(
'location' => 'Central>Europe>Italy',
'Total_S' => 4,
'Total_R' => 0,
),
array(
'location' => 'Central>Europe>Spain',
'Total_S' => 4,
'Total_R' => 0,
),
array(
'location' => 'Central>Africa>Egypt',
'Total_S' => 4,
'Total_R' => 0,
),
);
$search = 'Central>Europe>*';
$sum = array_sum(
array_column(
array_filter(
$data,
function($value) use ($search) {
return fnmatch($search, $value['location']);
}
),
'Total_S'
)
);
var_dump($sum);
编辑
对于没有array_column()函数的早期PHP版本:
$column = 'Total_S';
$sum = array_sum(
array_map(
function($value) use ($column) {
return $value[$column];
},
array_filter(
$data,
function($value) use ($search) {
return fnmatch($search, $value['location']);
}
)
)
);
(用5.3.27测试)
编辑# 2
修改: return = array_sum(
, return array_sum(
$searchSubset = array_filter(
$data,
function($value) use ($search) {
return fnmatch($search, $value['location']);
}
);
function summer($data, $column) {
return array_sum(
array_map(
function($value) use ($column) {
return $value[$column];
},
$data
)
);
}
$sumS = summer($searchSubset, 'Total_S');
$sumR = summer($searchSubset, 'Total_R');