search

Home  >  Q&A  >  body text

PHP array comparison unset problem

According to the value 5 4 1 contained in array two, unset the above array one without the key 5 4 1 to find the simplest way to write it. ha

// 数组一
array(6) {
  [1] => string(12) "伊凡木门"
  [2] => string(12) "梦天木门"
  [3] => string(15) "大自然地板"
  [4] => string(12) "尚品宅配"
  [5] => string(15) "德国都芳漆"
  [6] => string(12) "左右沙发"
}
数组二
array(3) {
  [0] => int(5)
  [1] => int(4)
  [2] => int(1)
}
三叔三叔2747 days ago1003

reply all(8)I'll reply

  • 高洛峰

    高洛峰2017-06-29 10:10:35

    I finally solved it with the following method. If the masters have a better way of writing, please feel free to enlighten me

        function get_vip_brand_list($uid = UID)
        {
            // 第一个数组
            $brand_list = config('sales_brand');
            // 第二个数组,反转键和值
            $node       = array_flip(get_auth_node($uid,'sales.brand'));
            // 比较两个数组的键名,并返回交集
            $vip_node   = array_intersect_key($brand_list, $node);
            return $vip_node;
        }
    

    reply
    0
  • PHP中文网

    PHP中文网2017-06-29 10:10:35

    You can use the functions of the array_diff series to operate. You can decide by yourself whether to use array_diff_key or assoc for the specific business.

    reply
    0
  • 世界只因有你

    世界只因有你2017-06-29 10:10:35

    According to the value 5 4 1 contained in array 2, find the simplest way to write the unset of the above array 1 which does not exist and the key is not 5 4 1. Ha
    means I don’t understand

    <?php
    $keys1 = array_keys($array1); // 获取数组1key列表
    $diffKeys = array_diff($keys1,$array2);// 结算数组1和数组2 key差集
    foreach($diffKeys as $key){
        unset($array1[$key]);
    }

    reply
    0
  • typecho

    typecho2017-06-29 10:10:35

    Create a new array to store the values ​​you want to retain. Then loop through array two, and then use the array_push function to push the values ​​to be retained in array one into the newly created array.

    reply
    0
  • 大家讲道理

    大家讲道理2017-06-29 10:10:35

    $arr1 = array(
        1 => "伊凡木门", 
        2 => "梦天木门",
        3 => "大自然地板",
        4 => "尚品宅配",
        5 => "德国都芳漆",
        6 => "左右沙发"
    );
    $arr2 = array(5, 4, 1);
    $keys = array_keys($arr1);
    $remove = array_diff($keys, $arr2);
    foreach ($remove as $key) {
        unset($arr1[$key]);
    }
    var_dump($arr1);

    reply
    0
  • 某草草

    某草草2017-06-29 10:10:35

    First flip array 2, and then find the intersection. I think your solution is the correct one

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-06-29 10:10:35

    foreach($arr2 as $value) {
        foreach($arr1 as $key => $val) {
            if($value == $key) {
                unset($arr1[$key]);
            }
        }
    }
    print_r($arr1);

    reply
    0
  • 学习ing

    学习ing2017-06-29 10:10:35

    You can learn about the array_slice function

    reply
    0
  • Cancelreply