-2

I am working on an indexing proj. its all fine up until when i have to udate the index file. i want whe a website is deleted by the admin, all its index posting lists should be deleted. please help by pointing me to the write way of removing an array from a mutlt dimensional array.

given an array like bellow, 3 is the id of the indexed website in the database. the admin deletes that website. I want also to be able to remove its posting references from my index.

Array
(
[mr] => Array
   (
        [3] => Array
            (
                [frequency] => 3
                [position] => Array
                    (
                        [0] => 16
                        [1] => 94
                        [2] => 110
                    )

            )

    )

[smith] => Array
    (
        [3] => Array
            (
                [frequency] => 3
                [position] => Array
                    (
                        [0] => 17
                        [1] => 95
                        [2] => 111
                    )

            )

    )
)

lets call that array $index. How can someone unset or delet all arrays that have a key of 3. meaning that i will be left with an array like this.

Array
(
[mr] => Array
(

 )

[smith] => Array
(

)
)
katwekibs
  • 1,342
  • 14
  • 17

1 Answers1

0

Very simple.

Loop through the first level array, and then loop through each second level array. If the second level key is 3, set the value at the first level array to be an empty array.

foreach($array as $key => $val) {
    foreach($val as $key2 => $val2) {
        if($key2 == 3) { unset($array[$key][$key2]); }
    }
}

Edited in response to below comment.

Ryan
  • 3,552
  • 1
  • 22
  • 39
  • What happens if 2nd level has more arrays? You will unset them all. Better solution would be do replace `$array[$key] = array();` with `unset($array[$key][$key2]);`. – Glavić Jan 13 '14 at 13:07
  • On looking at the question for a second time, I **presumed** only one array would exist for each second index. I've changed my code. – Ryan Jan 13 '14 at 13:09
  • Your answer before only worked if it is only one array; this now works for both cases. – Glavić Jan 13 '14 at 13:11
  • This will empty the whole $array[$key] remember its an index which might have other keys lets say there is another indexed webist with an id 4 another id 5. we dont want to delte them but rather target a specific one. like for example three. – katwekibs Jan 13 '14 at 13:11
  • Yeah, like I say for some reason I presumed each first-level array value would only contain one further value. The code has changed to allow that! – Ryan Jan 13 '14 at 13:12