Junaid
Junaid

Reputation: 488

PHP - Remove item from array by given key paths (in another array)

Here I have a problem to be solved. There will be two arrays:

<?php
$main_array = array(
  'item-1' => array(
    'item-1-1' => array(
      'item-1-1-1' => 'value',
      'item-1-1-2' => 'value',
    ),
    'item-1-2' => 'value'
  ),
  'item-2' => 'value',
  'item-3' => array(
    'item-3-1' => array(
      'item-3-1-1' => 'value',
      'item-3-1-2' => 'value',
    ),
    'item-3-2' => 'value',
  ),
);

$key_paths_to_deleted = array(
  array('item-1', 'item-1-1', 'item-1-1-1'),
  array('item-2'),
  array('item-3', 'item-3-1'),
);

I need to remove items from $main_array based index path given in $key_paths_to_deleted. So resulting $main_array should be as given below.

$main_array = array(
  'item-1' => array(
    'item-1-1' => array(
      'item-1-1-2' => 'value',
    ),
    'item-1-2' => 'value'
  ),
  'item-3' => array(
    'item-3-2' => 'value',
  ),
);

That means I will have 'path's to the items in main array to be removed.

Key and values in main array can be any possible values in PHP, no structured naming for keys, and values may be duplicate.

Thanks in advance.

Upvotes: 1

Views: 359

Answers (1)

fdehanne
fdehanne

Reputation: 1718

Function remove() is recursive and will check key in parameter. If key is found, it will delete it.

Parameter $last indicate if it's last key. In your example, it will delete all content of item-3-1 but not delete item-3

function remove(&$array, $remove, $last = false)
{
  foreach($array as $key => &$value) {
    if(is_array($value)) remove($value, $remove, $last);

    if(is_array($value) && $key == $remove && $last == true) unset($array[$key]);
    if( !is_array($value) && $key == $remove) unset($array[$key]);
  }
}

for ( $i = 0 ; $i < count($key_paths_to_deleted) ; $i++ )
{
  $last = count($key_paths_to_deleted[$i]) - 1;

  for ( $j = $last; $j >= 0 ; $j-- )
    remove($main_array, $key_paths_to_deleted[$i][$j], ( $j == $last ) ? true : false);
}

Result :

Array
(
    [item-1] => Array
        (
            [item-1-1] => Array
                (
                    [item-1-1-2] => value
                )

            [item-1-2] => value
        )
    [item-3] => Array
        (
            [item-3-2] => value
        )
)

Upvotes: 0

Related Questions