Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/269.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何根据PHP中匹配的值推送值_Php_Php 7 - Fatal编程技术网

如何根据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

解释

  • 步骤1=>
    $first
    数组我存储的是类的类型,比如类 1类为A型,2类为A型,3类为 B
  • 步骤2=>
    $second
    我正在存储类和值的数组键 爱好
  • 步骤3=>
    $second
    数组我想从
    $first
    数组中推送
    类型
    基于类什么是类型
  • 我已经写了PHP代码,我也得到了我预期的结果,但我是两个foreach然后如果条件,我认为这不是正确的方式来写。有没有办法优化我的代码

    我的代码

    $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'];
        }
    }