I have an array with 100 values(array1). I have another array with 8 values(array2). I want to take the values from array2 and use them as keys and extract the values in array1
Try this. loop the 2nd array and extract the value from array1 with using value of array2 as index for array1
foreach ( $array2 as $arr2 ){
$temp[]= $array[ $arr2 ];
}
return $temp;
something like this one:
function combine($array1, $array2) {
$array3 = array();
foreach ($array2 as $key => $value) { //loop through all entries of array2
//get the entry of array1 that corresponds to the value of array2's entry
if (isset($array1[$value]) {
$array3[$key] = $array1[$value]
}
}
return $array3;
}
I haven't tested it but it should give you something for thought.
you can use below code
function array_combine2($arr1, $arr2) {
foreach($arr2 as $val){
$arr3[] = $arr1[$val];
}
return $arr3;
}
For inctanse,
$arr1['x'] = 2;
$arr1['y'] = 3;
$arr1['z'] = 4;
$arr2[0] = 'x';
$arr2[1] = 'y';
$arr2[2] = 'z';
the above function will return the below as resbonse
$arr3[0] = 2;
$arr3[1] = 3;
$arr3[2] = 4;
Unfortunately, array_slice()
will disregard any association between the arrays based on keys/indexes. array_slice()
operates using offset
values; this is why it is the wrong tool for the job.
array_intersect_key()
is a suitable call to filter an array using another array's keys.
Code: (Demo)
for($char='A',$score=100; $score>0; ++$char,--$score){
$dr_img_scores1["IMG_$char"]=$score; // generate 100 unique elements
}
//var_export($dr_img_scores1); // uncomment to see what this looks like
// eight arbitrary elements to use as extraction keys on $array1
$dr_img_scores2=['IMG_CL'=>13,'IMG_Z'=>44,'IMG_BP'=>82,'IMG_L'=>50,
'IMG_CD'=>2,'IMG_X'=>91,'IMG_BM'=>7,'IMG_AV'=>0];
var_export(array_intersect_key($dr_img_scores1,$dr_img_scores2));
// notice that $dr_img_scores1's element order is preserved
Output:
array (
'IMG_L' => 89,
'IMG_X' => 77,
'IMG_Z' => 75,
'IMG_AV' => 53,
'IMG_BM' => 36,
'IMG_BP' => 33,
'IMG_CD' => 19,
'IMG_CL' => 11,
)
Note: If $dr_img_scores1
or $dr_img_scores2
are not in order, you can use ksort()
on them to synchronize their orders to permit an easy visual comparison of scores.