2014-02-04 2 views
2

Я пытаюсь удалить объект из массива объектов по его индексу. Вот что у меня до сих пор, но я в тупике.php удалить объект из массива объектов

$index = 2; 

$objectarray = array(
0=>array('label'=>'foo', 'value'=>'n23'), 
1=>array('label'=>'bar', 'value'=>'2n13'), 
2=>array('label'=>'foobar', 'value'=>'n2314'), 
3=>array('label'=>'barfoo', 'value'=>'03n23') 
); 

//I've tried the following but it removes the entire array. 
foreach ($objectarray as $key => $object) { 
if ($key == $index) { 
    array_splice($object, $key, 1); 
    //unset($object[$key]); also removes entire array. 
} 
} 

Любая помощь будет принята с благодарностью.

Обновлено решение

array_splice($objectarray, $index, 1); //array_splice accepts 3 parameters 
    //(array, start, length) removes the given array and then normalizes the index 
    //OR 
    unset($objectarray[$index]); //removes the array at given index 
    $reindex = array_values($objectarray); //normalize index 
    $objectarray = $reindex; //update variable 
+0

Что вы пытаетесь удалить именно? – FabioG

+0

'2 => array ('label' => 'foobar', 'value' => 'n2314'' – toddsby

ответ

7
array_splice($objectarray, $index, 1); 
    //array_splice accepts 3 parameters (array, start, length) and removes the given 
    //array and then normalizes the index 
    //OR 
    unset($objectarray[$index]); //removes the array at given index 
    $reindex = array_values($objectarray); //normalize index 
    $objectarray = $reindex; //update variable 
2

Вы должны использовать функцию unset в массиве.

Так его так:

<?php 

$index = 2; 

$objectarray = array(
    0 => array('label' => 'foo', 'value' => 'n23'), 
    1 => array('label' => 'bar', 'value' => '2n13'), 
    2 => array('label' => 'foobar', 'value' => 'n2314'), 
    3 => array('label' => 'barfoo', 'value' => '03n23') 
); 
var_dump($objectarray); 
foreach ($objectarray as $key => $object) { 
    if ($key == $index) { 
     unset($objectarray[$index]); 
    } 
} 

var_dump($objectarray); 
?> 

Помните, что ваш массив будет иметь нечетные индексы после этого и вы должны (если вы хотите) индексировать его.

$foo2 = array_values($objectarray); 
+0

« у вашего массива будут нечетные индексы ... ». Вы решили мою проблему. Thx – Coisox

2

в этом случае вам не нужно будет что Еогеасп только отключенное непосредственно

unset($objectarray[$index]); 
+0

Не работает, также удаляется весь массив. – toddsby

+0

@toddsby это должно быть что-то еще ... Я только что проверил это, и он отлично работает. Вы делаете какие-либо unsets после этого или раньше? – FabioG

+0

Вы были правы, у меня было неправильное утверждение if, предшествующее этому код, вызывающий '$ objectarray = '';'. Ваше решение работает, но я думаю, что 'array_splice' будет более эффективным для моего варианта использования. Я обновил свой вопрос. – toddsby

Смежные вопросы