如果第一个字段liked_cnt , coupon_cnt
相同,我想要将两个数组字段id
相加
我怎么能这样做?
我这样做但是太慢了
if (end($like)['id'] > end($coupon)['id']) {
$i = end($like)['id'];
$j = end($coupon)['id'];
}else {
$i = end($coupon)['id'];
$j = end($like)['id'];
}
for ($k=0; $k <= $i; $k++) {
for ($l=0; $l < $j; $l++) {
if ($like['id'] == $coupon['id']) {
$score[$like['id']] = ($coupon['coupon_cnt'] * 1000) + $like['liked_cnt'];
}else {
$score[$i] = 0;
}
}
}
//first array $Like
Array ( [0] => Array ( [id] => 85 [liked_cnt] => 6 ) [1] => Array ( [id] => 86 [liked_cnt] => 14 ) [2] => Array ( [id] => 92 [liked_cnt] => 6 ) [3] => Array ( [id] => 93 [liked_cnt] => 6 )
//second array $coupon
Array ( [0] => Array ( [id] => 35 [coupon_cnt] => 2 ) [1] => Array ( [id] => 86 [coupon_cnt] => 1 ) [2] => Array ( [id] => 139 [coupon_cnt] => 1 ) )
答案 0 :(得分:1)
没有内置于php的魔术算法能够以更有效的方式真正计算出您想要的结果。这可能稍微有点效率,但最重要的是它更具可读性:
content-length →0
content-type →application/json
status →200
via →1.1 swfbfbbaf3fb6c32bdccb152354539e473d.cloudfront.net (CloudFront)
x-amz-cf-id →K9V3XUxHOretrza0kCM5dk_G5eZgePrtrBziyVTxptrePD7wjsWqk-l0kCQQ==
x-amzn-requestid →5ac81024-5c27-11e7-af9a-9f3c8494c542
x-amzn-trace-id →Root=1-5953e77f-ed76d15b5bfre9374c9
输出显然是:
<?php
$input = [
[
['id' => 85, 'liked_cnt' => 6],
['id' => 86, 'liked_cnt' => 14],
['id' => 92, 'liked_cnt' => 6],
['id' => 93, 'liked_cnt' => 6]
],
[
['id' => 35, 'coupon_cnt' => 2],
['id' => 86, 'coupon_cnt' => 1],
['id' => 139, 'coupon_cnt' => 1]
]
];
$output = [];
foreach ($input as $set) {
array_walk($set, function($entry) use (&$output) {
$count = array_pop($entry);
$id = array_pop($entry);
if (array_key_exists($id, $output)) {
$output[$id]['total_cnt'] += $count;
} else {
$output[$id] = ['id' => $id, 'total_cnt' => $count];
}
});
}
print_r(array_values($output));
更新:
考虑到下面的第三条评论,我添加了这个修改后的版本,将Array
(
[0] => Array
(
[id] => 85
[total_cnt] => 6
)
[1] => Array
(
[id] => 86
[total_cnt] => 15
)
[2] => Array
(
[id] => 92
[total_cnt] => 6
)
[3] => Array
(
[id] => 93
[total_cnt] => 6
)
[4] => Array
(
[id] => 35
[total_cnt] => 2
)
[5] => Array
(
[id] => 139
[total_cnt] => 1
)
)
属性的一般乘法引入因子1000:
coupon_cnt