3 回答

TA貢獻1775條經驗 獲得超8個贊
您可以通過使用;按值重新索引$encoded
數組來使您的生活更輕松。那么您不必每次都搜索數組來查找值,您可以直接使用.?提取數據后,您可以使用按值排序:encoder_id
array_column
user_id
isset
usort
encoded
$encoded_ids = array_column($encoded, null, 'encoder_id');
$data = array();
foreach ($profiles as $profile) {
? ? $user_id = $profile['user_id'];
? ? if (isset($encoded_ids[$user_id])) {
? ? ? ? $data[] = array('id' => $user_id,
? ? ? ? ? ? ? ? ? ? ? ? 'fullname' => $encoded_ids[$user_id]['fullname'],
? ? ? ? ? ? ? ? ? ? ? ? 'encoded' => $encoded_ids[$user_id]['encoded']
? ? ? ? ? ? ? ? ? ? ? ? );
? ? }
? ? else {
? ? ? ? $data[] = array('id' => $user_id,
? ? ? ? ? ? ? ? ? ? ? ? 'fullname' => "${profile['first_name']} ${profile['middle_name']} ${profile['last_name']}",
? ? ? ? ? ? ? ? ? ? ? ? 'encoded' => 0
? ? ? ? ? ? ? ? ? ? ? ? );
? ? }
}
usort($data, function ($a, $b) { return $b['encoded'] - $a['encoded'];});
print_r($data);
輸出:
Array
(
? ? [0] => Array
? ? ? ? (
? ? ? ? ? ? [id] => 23b1f4a2-034c-43b4-96b7-3191d78cead1
? ? ? ? ? ? [fullname] => John L. Walker
? ? ? ? ? ? [encoded] => 20
? ? ? ? )? ??
? ? [1] => Array
? ? ? ? (
? ? ? ? ? ? [id] => 0d31557d-1e9f-4db3-ac0d-72e1709fe89c
? ? ? ? ? ? [fullname] => Randy O. Rocker
? ? ? ? ? ? [encoded] => 10
? ? ? ? )? ??
? ? [2] => Array
? ? ? ? (
? ? ? ? ? ? [id] => fcc3d884-fbef-438a-9c86-0ad52c9b1223
? ? ? ? ? ? [fullname] => Nar?ia ? Cruz
? ? ? ? ? ? [encoded] => 0
? ? ? ? )? ??
? ? [3] => Array
? ? ? ? (
? ? ? ? ? ? [id] => 0f93f169-cf56-49df-a76b-7596446104c6
? ? ? ? ? ? [fullname] => Qwerty K Asdfg
? ? ? ? ? ? [encoded] => 0
? ? ? ? )? ??
)

TA貢獻1776條經驗 獲得超12個贊
使用array_reduce
:
$encodedByEncoderId = array_column($encoded, null, 'encoder_id');
$combined = array_reduce($profiles, function (array $combined, array $profile) use ($encodedByEncoderId): array {
? $combined[] = [
? ? 'id' => $profile['user_id'],
? ? 'fullname' => $encodedByEncoderId[$profile['user_id']]['fullname']?
? ? ? ?? "{$profile['first_name']} {$profile['middle_name']}. {$profile['last_name']}",
? ? 'encoded' => $encodedByEncoderId[$profile['user_id']]['encoded']?
? ? ? ?? 0
? ];
? return $combined;
}, []);
演示: https:?//3v4l.org/kKBru

TA貢獻1810條經驗 獲得超4個贊
嘗試這個!
$data = [];
foreach ($profiles as $key => $val) {
$user_id = $val['user_id'];
$is_matched = 0;
$encoded_data = [];
foreach($encoded as $k => $v){
if ($user_id == $v['encoder_id']) {
$is_matched = 1;
$encoded_data = $v;
}
}
$ext_name = ($val['ext'] == '') ? '' : $val['ext'];
$fullname = $val['first_name'].' '.substr($val['middle_name'], 0, 1).'. '.$val['last_name'].' '.$ext_name;
$data[$key] = array(
'id' => ($is_matched == 1) ? $encoded_data['encoder_id'] : $user_id,
'fullname' => ($is_matched == 1) ? $encoded_data['fullname'] : $fullname,
'encoded' => ($is_matched == 1) ? $encoded_data['encoded'] : 0
);
}
- 3 回答
- 0 關注
- 141 瀏覽
添加回答
舉報