我被PHP程序卡住了。
我有2个数组(1是关联数组),来自2个不同的来源:
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"
}
因此,我需要一个名为array3的关联数组,它具有array1的所有“瓦尔”,这些“Val”具有属性“gr_id”== 33,如果这个值在array2中,则第二个属性称为selected:
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)
}
我尝试了foreach和for循环,但我无法找到解决方案:
$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条答案
按热度按时间pbwdgjma1#
siv3szwd2#
我认为array_map是你正在寻找的功能。
并将此函数调用为
$array3 = array_map('checkValue', $array1);
oknrviil3#
如何使用array_filter和array_walk: