我有2个数组$userArray
和$differentArray
。
问题:我正在尝试查找$userArray
的{{1}}与$userId
匹配的索引值,以便我可以提取姓/名
$differentArray
输出:
print_r
$ differentRrray的 Array
(
[0] => Array
(
[userId] => ID Object
(
[_unknown:protected] =>
[id_:protected] => 8k6Y4FTrnxKY45XrVkXvVJhL
)
[firstName] => Joe
[lastName] => Smith
)
[2] => Array
(
[userId] => ID Object
(
[_unknown:protected] =>
[id_:protected] => pCvR9qvIgGv8WyejcKmRtGD8
)
[firstName] => Sue
[lastName] => Miller
)
)
输出:
print_r
这是我的尝试,但它只输出Joe Smith
* Array
(
[0] => Array
(
[date] => 1363800434868
[userId] => ID Object
(
[_unknown:protected] =>
[id_:protected] => 8k6Y4FTrnxKY45XrVkXvVJhL
)
[someTxt] => aaaa
)
[1] => Array
(
[date] => 1363800858828
[userId] => ID Object
(
[_unknown:protected] =>
[id_:protected] => 8k6Y4FTrnxKY45XrVkXvVJhL
)
[someTxt] => cccc
)
[2] => Array
(
[date] => 1363817564430
[userId] => ID Object
(
[_unknown:protected] =>
[id_:protected] => pCvR9qvIgGv8WyejcKmRtGD8
)
[someTxt] => ccc
)
)
的构建方式与$differentArray
$userArray
谢谢。
答案 0 :(得分:1)
伙计,使用foreach
。
$i = 0;
while ($i < $total) {
$userId = $differentArray[$i]['userId'];
// $key = array_search($userId, $userArray);
foreach ($userArray as $k => $user) {
if($user["userId"] == $userId){
$key = $k;
break; // avoid useless loop
}
}
$firstName = $userArray[$key]['firstName'];
$lastName = $userArray[$key]['lastName'];
$i++;
}
答案 1 :(得分:1)
我不确定那个ID对象是什么,但我认为它有一个返回id属性的__toString方法。
$output = array();
foreach ($differentArray as $user) {
foreach ($userArray as $searchedUser) {
if ($searchedUser['userId'] == $user['userId']) {
$output[] = $searchedUser;
}
}
}
这将把你正在寻找的用户放在$ output数组中。这样你就不再需要索引了。您可以迭代$ output以将值拉出到变量。例如
foreach ($output as $user) {
list($userId, $firstName, $lastName) = $user;
// do your code here
}
如果您确定$ userArray中只能有一个匹配,那么当您找到它或从$ output数组中拉出第一个匹配时,您可以从循环中突破。
我做了很多猜测,因为你没有提供$ differentArray结构,也没有说明你实际期望的结果。