我有两个不同字段的数组,第一个数组是用户信息,第二个是用户优惠券号码。
如果两个数组ID相等
,我想要total = (coupon_cnt * 1000) + liked_cnt
我写了这段代码,但这不会返回用户信息
$input = array($like , $coupon);
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]['user_score'] += 1000 * $count;
} else {
$output[$id] = ['id' => $id, 'user_score' => $count];
}
});
}
$score = array_values($output);
阵列
$like = Array
(
[0] => Array
(
[id] => 85
[user_phone] => 00000000
[user_email] => test@gmail.com
[user_name] => test
[user_password] => test
[user_city] => 1
[user_picture] => V5XgNt6P3BhT9iucdv_photo_001.jp
[user_coupon_token] => 43131
[user_post_hour] => 10
[user_is_block] => 0
[user_reg_date] => 2017-05-16 13:52:35
[last_ip] =>
[user_push_token] =>
[liked_cnt] => 6 <-- I want add this to coupon_cnt * 1000
)
)
$coupon = Array
(
[0] => Array
(
[id] => 85
[coupon_cnt] => 2
)
[1] => Array
(
[id] => 86
[coupon_cnt] => 1
)
[2] => Array
(
[id] => 139
[coupon_cnt] => 1
)
)
输出
$output = Array
(
[0] => Array
(
[id] => 85
[user_phone] => 00000000
[user_email] => test@gmail.com
[user_name] => test
[user_password] => test
[user_city] => 1
[user_picture] => V5XgNt6P3BhT9iucdv_photo_001.jp
[user_coupon_token] => 43131
[user_post_hour] => 10
[user_is_block] => 0
[user_reg_date] => 2017-05-16 13:52:35
[last_ip] =>
[user_push_token] =>
[output] => 2006 <-- I want this
)
)
任何人都可以提供帮助吗?
答案 0 :(得分:0)
首先让第二个阵列更容易管理:
$easierToManageSecondArray = array_column($coupon, "coupon_cnt", "id");
然后&#34;循环&#34;:
$like = array_map(function ($value) use ($easierToManageSecondArray) {
if (isset($easierToManageSecondArray[$value["id"]]) {
$value["user_score"] = ($easierToManageSecondArray[$value["id"]] * 1000) + $value["liked_cnt"];
} else {
$value["user_score"] = $value["liked_cnt"]; //No idea if this makes sense.
}
return $value;
}, $like);
答案 1 :(得分:0)
检查以下代码:
$like = Array
(
0 => Array
(
'id' => 85,
'user_phone' =>' 00000000',
'user_email' => 'test@gmail.com',
'user_name' => 'test',
'user_password' => 'test',
'liked_cnt' => 6
)
);
$coupon = Array
(
0 => Array
(
'id' => 85,
'coupon_cnt' => 2
),
1 => Array
(
'id' => 86,
'coupon_cnt' => 1
)
);
foreach($like as $key => $value){
foreach($coupon as $value2){
if($value['id'] === $value2['id']){
$like[$key]['liked_cnt'] += $value2['coupon_cnt'] * 1000;
}
}
}
print_r($like);
<强>输出强>
Array
(
[0] => Array
(
[id] => 85
[user_phone] => 00000000
[user_email] => test@gmail.com
[user_name] => test
[user_password] => test
[liked_cnt] => 2006
)
)
演示:Click Here