如何根据 PHP 中的匹配值推送值
How to push the value, based on matched value in PHP
$first = [
["class" => "1", "type" => "A"],
["class" => "2", "type" => "A"],
["class" => "3", "type" => "B"]
];
$second = [
"1" => ["hobbies" => ["A" , "B"] ],
"2" => ["hobbies" => ["A" ] ],
"3" => ["hobbies" => [ "C" ] ]
];
说明
- 第 1 步 =>
$first
数组我正在存储 class 明智的类型,如 class
1 类型为 A & class 2 类型为 A & class 3 类型为
B
- 第 2 步 =>
$second
我正在存储 class 和值的数组键
爱好
- 第 3 步 =>
$second
数组我想从 $first
数组推送 type
基于class什么是类型
我已经写了 PHP 代码,我也得到了预期的结果,但我是两个 foraech 然后如果条件,我认为这不是正确的编写方式。有什么方法可以优化我的代码吗?
我的代码
foreach ($second as $class => $value) {
foreach ($first as $key => $temp) {
if($class == $temp['class'] ){
$second[$class]['Type'] = $temp['type'];
}
}
}
echo "<pre>";
print_r($second);exit;
我的预期答案
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
)
)
由于 $second
中的键与 $first
中的 class
相同,您可以这样做:
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'];
}
}
此代码将仅使用一个 foreach
超过 $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" ] ]
];
说明
- 第 1 步 =>
$first
数组我正在存储 class 明智的类型,如 class 1 类型为 A & class 2 类型为 A & class 3 类型为 B - 第 2 步 =>
$second
我正在存储 class 和值的数组键 爱好 - 第 3 步 =>
$second
数组我想从$first
数组推送type
基于class什么是类型
我已经写了 PHP 代码,我也得到了预期的结果,但我是两个 foraech 然后如果条件,我认为这不是正确的编写方式。有什么方法可以优化我的代码吗?
我的代码
foreach ($second as $class => $value) {
foreach ($first as $key => $temp) {
if($class == $temp['class'] ){
$second[$class]['Type'] = $temp['type'];
}
}
}
echo "<pre>";
print_r($second);exit;
我的预期答案
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
)
)
由于 $second
中的键与 $first
中的 class
相同,您可以这样做:
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'];
}
}
此代码将仅使用一个 foreach
超过 $first
数组。