I have 2 arrays $userArray
and $differentArray
.
question: I am trying to find the index value from $userArray
where $userId
matches from $differentArray
so that i can pull the first/last names
print_r
of $userArray outputs this:
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
of $differentArray outputs this:
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
)
)
and here is my attempt, but it only outputs Joe Smith
* $differentArray
is constructed the same way as $userArray
$i = 0;
while ($i < count($differentArray)){
$userId = $differentArray[$i]['userId'];
$key = array_search( $userId, $userArray );
$firstName = $userArray[$key]['firstName'];
$lastName = $userArray[$key]['lastName'];
$i++;
}
thank you.
Man, use 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++;
}
I'm not sure what that ID object is, but I assume it has a __toString method that returns the id property.
$output = array();
foreach ($differentArray as $user) {
foreach ($userArray as $searchedUser) {
if ($searchedUser['userId'] == $user['userId']) {
$output[] = $searchedUser;
}
}
}
That will put the users you're looking for in $output array. This way you won't need the indices no more. You can just iterate over $output to pull out the values to variables. Eg.
foreach ($output as $user) {
list($userId, $firstName, $lastName) = $user;
// do your code here
}
If you're certain that there can only be one match in $userArray than you can break out from the loop when you find it or pull out the first one from the $output array.
I did a lot of guessing posting that answer since you didn't provide the $differentArray structure nor specified what it is you're actually expecting.