Dimas Prayoga
Dimas Prayoga

Reputation: 47

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 :

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

Upvotes: 0

Views: 69

Answers (1)

Erfan Bahramali
Erfan Bahramali

Reputation: 410

You need a loop for the main array and a loop for the internal arrays

So it is better to put 2 loop inside each other

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:

$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
)

Upvotes: 2

Related Questions