我的基本数组结构如下
$user_data = [
[
'user_id' => '1',
'user_name' => 'numpty',
'email' => 'john@somewhere.com',
'first_name' => 'John',
'last_name' => 'Smith'
],
[
'user_id' => '2',
'user_name' => 'fairy52',
'email' => 'natasha@legs.com',
'first_name' => 'Natasha',
'last_name' => 'Jones'
],
[
'user_id' => '3',
'user_name' => 'angie_turmoil',
'email' => 'ange@nightmare.com',
'first_name' => 'Angela',
'last_name' => 'Swift'
],
[
'user_id' => '4',
'user_name' => 'dastardly_dan',
'email' => 'daniel@aol.com',
'first_name' => 'Daniel',
'last_name' => 'McNash'
],
[
'user_id' => '5',
'user_name' => 'horse',
'email' => 'fred@features.com',
'first_name' => 'Frederick',
'last_name' => 'Walsh'
]
];
$user_followers = [
[
'user_id' => '1',
'followers' => ['3', '4', '5']
],
[
'user_id' => '2',
'followers' => ['1', '5']
],
[
'user_id' => '3',
'followers' => ['1', '5', '4']
],
[
'user_id' => '4',
'followers' => ['3', '1', '5']
],
[
'user_id' => '5',
'followers' => ['1', '2', '4']
],
];
我需要做的是为每个$user_data
根据user_id
返回关注者名称,因此$user_data
中的第一条记录需要返回姓名
angie_turmoil
dastardly_dan
horse
据我所知,这不是传统的数据存储方式,但它是学习OOP PHP的原型项目,我不需要使用数据库进行数据存储。
答案 0 :(得分:0)
正如您当前构建的数据一样,如果您想尝试简单的foreach,您可以执行类似的操作。考虑这个例子:
$data = array();
foreach($user_followers as $index => $element) {
$current_user = $element['user_id']; // get the current user in iteration
$followers = $element['followers']; // get his/her followers
foreach($followers as $f_user_id) {
foreach($user_data as $key => $value) { // search the current user followers inside the user_data
if($value['user_id'] == $f_user_id) {
$data[$current_user]['follower_names'][] = $value['user_name'];
}
}
}
}
print_r($data);
示例输出:
Array
(
[1] => Array
(
[follower_names] => Array
(
[0] => angie_turmoil
[1] => dastardly_dan
[2] => horse
)
)
[2] => Array
(
[follower_names] => Array
(
[0] => numpty
[1] => horse
)
)
[3] => Array
(
[follower_names] => Array
(
[0] => numpty
[1] => horse
[2] => dastardly_dan
)
)
// and so on.
注意:他们的数组键是user_id,里面的值是他们的追随者。
答案 1 :(得分:0)
这有点疯狂,但嘿,它有效:
$list = array();
foreach ($user_data as $user)
foreach ($user_followers as $followers)
if ($followers['user_id']==$user['user_id'])
foreach ($followers['followers'] as $f_id)
foreach ($user_data as $user2)
if ($user2['user_id']==$f_id)
$list[$user['user_name']][] = $user2['user_name'];
print_r($list);
输出:
Array
(
[numpty] => Array
(
[0] => angie_turmoil
[1] => dastardly_dan
[2] => horse
)
[fairy52] => Array
(
[0] => numpty
[1] => horse
)
[angie_turmoil] => Array
(
[0] => numpty
[1] => horse
[2] => dastardly_dan
)
[dastardly_dan] => Array
(
[0] => angie_turmoil
[1] => numpty
[2] => horse
)
[horse] => Array
(
[0] => numpty
[1] => fairy52
[2] => dastardly_dan
)
)