0

I have an array

Array
(
    [0] => 4
    [1] => 5
)

and other one

Array
(
    [0] => Array
        (
            [v1] => aa
            [v2] => ss
        )
.
.
.
.

    [4] => Array
        (
            [v1] => vv
            [v2] => dd
        )

    [5] => Array
        (
            [v1] => gg
            [v2] => rr
        )
)

The question, how can I get results from the second array using values in the first one. The output should be looking like this

[4] => Array
    (
        [v1] => vv
        [v2] => dd
    )

[5] => Array
    (
        [v1] => gg
        [v2] => rr
    )

I'm trying some function like array_intersect and array_values but It didn't work.

0

5 Answers 5

2

You can use array_intersect_key and array_flip:

$result = array_intersect_key($secondArray, array_flip($firstArray));
Sign up to request clarification or add additional context in comments.

2 Comments

Ha. Didn't see your answer before I posted my (identical) answer. Great minds eh? ;)
:) no problem.. there are a lot of answers using the foreach loop but we thought it will be nicer to use these built in functions :)
1

This would iterate trough the first array and get the values from the second array.

$newarray=array();
foreach ($array1 as $v) {
    $newarray[$v] = $array2[$v];
}

1 Comment

No problem, don't forget to pick an accepted answer then ;) Also thank you @Sougata for the answer improvement.
0

try doing something like this

$array_a;/* 
    Array
    (
        [0] => 4
        [1] => 5
    )*/
    $result = array() ;
    foreach ($array_a as $res){
        if ( array_key_exists($array_b[$res])  ){
            $result[] = $array_b[$res] 
        }
    }

Comments

0

You may do it like this:

$output = array();

foreach( $first_array as $v ){
    $output[$v] = $second_array[$v];
}

//$output has
//[4] => Array
//(
//    [v1] => vv
//    [v2] => dd
//)

//[5] => Array
//(
//    [v1] => gg
//    [v2] => rr
//)

1 Comment

Thank you . . I have more than one key, is it work ?
0

This is the executed code.

<?php

 $array1 = array(3,5);

 echo '<pre>';
 print_r($array1);

 $array2 = array();
 $array2[0] = array('v1'=>'aa','v2'=>'ss');
 $array2[3] = array('v1'=>'vv','v2'=>'dd');
 $array2[4] = array('v1'=>'xx','v2'=>'yy');
 $array2[5] = array('v1'=>'gg','v2'=>'rr');
 print_r($array2);

 $array3 = array();
 for($i=0;$i<=count($array1)-1;$i++)
 {
    if (array_key_exists($array1[$i], $array2))
          $array3[$array1[$i]] = $array2[$array1[$i]];
 }  

 print_r($array3);

 ?>

3 Comments

Well that's one old way of doing it.
may be but it results the same which is requested. :)
Yeah, it's a valid solution but it costs more coding than a simple foreach

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.