0

I have a multi dimensional array like below.

array:1 [
  0 => array:3 [
    "picture_id" => "0"
    "car_name" => "CA"
    "from" => "2020"
    "to" => "2020"
  ]
]

I need to remove from & to from the above array and return result in same structure.

I have tried following code

    $whitelist = array("from", "to");
    $finalArray = [];
    foreach ($records as $record) {
        foreach ($record as $key => $item) {
            if (!in_array($key, $whitelist)) {
                $finalArray[$key] = $item;
            }
        }
    }

But the result I am getting is not multi-dimensional array like this:

array:1 [
  "picture_id" => "0"
  "car_name" => "CA"
]

My expected result is:

array:1 [
  0 => array:3 [
    "picture_id" => "0"
    "car_name" => "CA"
  ]
]
S S
  • 1,443
  • 2
  • 12
  • 42

3 Answers3

5

You can try something like this:

$array = [
   [
    "picture_id" => "0",
    "car_name" => "CA",
    "from" => "2018",
    "to" => "2020"
  ],
       [
    "picture_id" => "1",
    "car_name" => "WA",
    "from" => "2010",
    "to" => "2019"
  ]
];

    $whitelist = array("from", "to");
    $finalArray = [];
    foreach ($array as $k =>  $record) {
        foreach ($record as $key => $item) {
            if (!in_array($key, $whitelist)) {
                $finalArray[$k][$key] = $item;
            }
        }
    }
print("<pre>".print_r($finalArray,true)."</pre>");

What will print out:

Array
(
    [0] => Array
        (
            [picture_id] => 0
            [car_name] => CA
        )

    [1] => Array
        (
            [picture_id] => 1
            [car_name] => WA
        )

)

A short explanation...Basically you are looping over multi dimensional array as

foreach($array as $key => $value)

Where value is "inner" array, so in order to remove some elements from inner, and create a new multi dimensionalarray, you have to use keys, like in my example, from original array. So you than actually make an array like:

$newArray[$key] = $innerArray

And this gives you multi dimensional array. BR

JureW
  • 641
  • 1
  • 6
  • 15
3

Rather than having to go through each field to determine if it should be removed, you can use array_diff_key() to remove all of the columns in one go. This needs you to create a list of the fields you want to remove and for each record just get the difference between the record and the keys to remove...

// Keys to remove (note as key rather than value)
$remove = ["from" => 1, "to" => 1];
$finalArray = [];
foreach ($array as $record) {
    $finalArray[] = array_diff_key($record, $remove);
}
print_r($finalArray);
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
2

Try This

$result = [];
foreach($yourArray as $key => $value){
  unset($value['from']);
  unset($value['to']);        //You can unset as many columns as you want specifically.
  $result[] = $value;
}
print_r($result);
Sandesh
  • 46
  • 2