简体   繁体   English

如何删除多维数组值PHP中不在数组中的值

[英]How to remove value where not in array in multidimensional array value PHP

This is $multidimensional data result:这是$多维数据结果:

[
    {
        "2018-11-02": [
            "2"
        ]
    },
    {
        "2018-11-02": [
            "8",
            "3"
        ]
    }
    {
        "2018-11-21": [
            "11",
            "35",
            "94",
            "98",
            "163"
        ]
    },
]

$filter = [3,98,11]

How to remove object and value in $multidimensional where value not exist in $filter and after unset, the result will be turned into an object like the one below:如何删除$multidimensional multidimensional 中的 object 和值,其中$filter中不存在值,取消设置后,结果将变成 object,如下所示:

{
  "3": 2018-11-02,
  "98": 2018-11-21,
  "11" : 2018-11-21
}

In my case, I am using unserialize:就我而言,我使用的是反序列化:

for($w=0;$w<count($multidimensional);$w++) {
      $hasilId2[] = (object) [
        $multidimensional[$w]->date=> unserialize($multidimensional[$w]->invoiceid)
      ];
    }

I've already try using loop:我已经尝试过使用循环:

foreach($multidimensional as $key => $value) {
      if(!in_array($key, $filter)) {
        unset($multidimensional[$key]);
      }
    }

You need a loop for the main array and a loop for the internal arrays您需要一个用于主阵列的循环和一个用于内部 arrays 的循环

So it is better to put 2 loop inside each other所以最好把2个循环放在一起

There is also no need to uset也没有必要使用

You can put the correct results in a separate variable and then use it您可以将正确的结果放在单独的变量中,然后使用它

You wanted the key to that array to be the final array value您希望该数组的键成为最终的数组值

So I used the key function to get the array key and gave the new value like this:所以我使用键 function 来获取数组键并给出如下新值:

$result[array value] = [array key];

And finally I printed the new array:最后我打印了新数组:

$multidimensional = [
    [
        "2018-11-02" => [
            "2"
        ]
    ],
    [
        "2018-11-02" => [
            "8",
            "3"
        ]
    ],
    [
        "2018-11-21" => [
            "11",
            "35",
            "94",
            "98",
            "163"
        ]
    ],
];

$filter = [3, 98, 11];
$result = [];
foreach ($multidimensional as $val1) {
    foreach (array_values($val1)[0] as $key => $val2) {
        if (in_array($val2, $filter)) {
            $result[$val2] = key($val1);
        }
    }
}
print_r($result);

Result:结果:

Array
(
    [3] => 2018-11-02
    [11] => 2018-11-21
    [98] => 2018-11-21
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM