如何根据PHP中匹配的值推送值
解释如何根据PHP中匹配的值推送值,php,php-7,Php,Php 7,解释 步骤1=>$first数组我存储的是类的类型,比如类 1类为A型,2类为A型,3类为 B 步骤2=>$second我正在存储类和值的数组键 爱好 步骤3=>$second数组我想从$first数组中推送类型 基于类什么是类型 我已经写了PHP代码,我也得到了我预期的结果,但我是两个foreach然后如果条件,我认为这不是正确的方式来写。有没有办法优化我的代码 我的代码 $first = [ ["class" => "1", "type" => "A"], ["c
$first
数组我存储的是类的类型,比如类
1类为A型,2类为A型,3类为
B$second
我正在存储类和值的数组键
爱好$second
数组我想从$first
数组中推送类型
基于类什么是类型$first = [
["class" => "1", "type" => "A"],
["class" => "2", "type" => "A"],
["class" => "3", "type" => "B"]
];
$second = [
"1" => ["hobbies" => ["A" , "B"] ],
"2" => ["hobbies" => ["A" ] ],
"3" => ["hobbies" => [ "C" ] ]
];
由于
$second
中的键与$first
中的类
相同,因此可以执行以下操作:
foreach ($first as $item) {
// check if there's a key `$item['class']` in `$second`:
if (isset($second[$item['class']])) {
$second[$item['class']]['type'] = $item['type'];
}
}
此代码将在$first
数组上仅使用一个foreach
Array
(
[1] => Array
(
[hobbies] => Array
(
[0] => A
[1] => B
)
[Type] => A
)
[2] => Array
(
[hobbies] => Array
(
[0] => A
)
[Type] => A
)
[3] => Array
(
[hobbies] => Array
(
[0] => C
)
[Type] => B
)
)
foreach ($first as $item) {
// check if there's a key `$item['class']` in `$second`:
if (isset($second[$item['class']])) {
$second[$item['class']]['type'] = $item['type'];
}
}