I’m stuck on php program.
I’ve 2 array (1 is associative array) that comes from 2 different sources:
echo('<pre>');
var_dump(array1)
echo('<pre>');
array(5) {
[2375]=>
array(4) {
["Val"]=>
string(1) "x"
["Desc"]=>
string(13) "Lorem ipsum 1"
["gr_id"]=>
string(2) "33"
}
[2377]=>
array(4) {
["Val"]=>
string(1) "y"
["Desc"]=>
string(13) "Lorem ipsum 2"
["gr_id"]=>
string(2) "33"
}
[2379]=>
array(4) {
["Val"]=>
string(1) "z"
["Desc"]=>
string(13) "Lorem ipsum 3"
["gr_id"]=>
string(2) "33"
}
[2381]=>
array(4) {
["Val"]=>
string(1) "a"
["Desc"]=>
string(13) "Lorem ipsum 4"
["gr_id"]=>
string(2) "33"
}
[2381]=>
array(4) {
["Val"]=>
string(34) "b"
["Desc"]=>
string(46) "Lorem ipsum 5"
["gr_id"]=>
string(2) "33"
}
[3300]=>
array(4) {
["Val"]=>
string(34) "c"
["Desc"]=>
string(46) "Lorem ipsum 5"
["gr_id"]=>
string(2) "83"
}
[3302]=>
array(4) {
["Val"]=>
string(34) "d"
["Desc"]=>
string(46) "Lorem ipsum 5"
["gr_id"]=>
string(2) "83"
}
var_dump(array2)
array(2) {
[0]=>
string(1) "x"
[1]=>
string(1) "a"
}
As a result I need an associative array called array3 that have all the "Val" of the array1 that have the property "gr_id" == 33, and a second property called selected if this value is in array2:
echo('<pre>');
var_dump(array3)
echo('<pre>');
array(5) {
[0]=>
array(4) {
["Val"]=>
string(1) "x"
["Selected"]=>
bool(true)
}
[1]=>
array(4) {
["Val"]=>
string(1) "y"
["Selected"]=>
bool(false)
}
[2]=>
array(4) {
["Val"]=>
string(1) "z"
["Selected"]=>
bool(false)
}
[3]=>
array(4) {
["Val"]=>
string(1) "a"
["Selected"]=>
bool(true)
}
[4]=>
array(4) {
["Val"]=>
string(1) "b"
["Selected"]=>
bool(false)
}
I tried foreach and for loop but I cannot came up with a solution:
$array3 = array();
foreach($rray1 as $Key => $Values){
$tempArr = array();
if($Values['gr_id'] == $GrID){
foreach($array2 as $ValueSelected){
$IsSelected = in_array($ValueSelected, $compareArr);
}
$tempArr[$GrID] = array(
'Descr' => $Values['Val'],
'Selected' => $IsSelected
);
array_push($array3 , $tempArr);
}
}
3
Answers
I think array_map is the function you are looking for.
And call this function as
$array3 = array_map('checkValue', $array1);
How about using array_filter and array_walk :