PHP array comparison unset problem
三叔
三叔 2017-06-29 10:08:35
0
8
934

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)
}
三叔
三叔

reply all(8)
小葫芦

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;
    }
Ty80

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.

世界只因有你

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]);
}
typecho

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.

大家讲道理
$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);
某草草

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

扔个三星炸死你
foreach($arr2 as $value) {
    foreach($arr1 as $key => $val) {
        if($value == $key) {
            unset($arr1[$key]);
        }
    }
}
print_r($arr1);
学习ing

You can learn about the array_slice function

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!