1

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.

2
  • what you tried ? Did you tried at all ? Commented Sep 17, 2014 at 10:06
  • Yes, I had tried and keep trying... Commented Sep 17, 2014 at 12:49

1 Answer 1

0

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
        )
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.