Skip to content
Advertisement

Relate data between two 2d arrays based on a shared value in a protected property

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++;
}

Advertisement

Answer

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++;
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement