2010-12-12 17 views
1

我的問題是類似這樣的單取消設置多維數組值,重新排序並返回到Php?

PHP | Remove element from array with reordering?

...除了當我返回有序陣列,我想的鑰匙,從1我的陣列開始,然而,是多維的。通過閱讀PhP手冊中關於array_values函數的註釋,我明白在鍵上會發生一些奇怪的事情(Carsten Milkau寫道:'請注意,在多維陣列中,每個元素可能由序列標識,即')

這讓我很困惑,因爲看起來我不能再簡單地使用foreach循環遍歷數組,並且每次向鍵值添加1。我非常感謝一些幫助,這一點,否則我將不得不實施一些嚴重的醜陋和冗長的變通...這裏是我的代碼:

// $orderedData contains, for example, $orderedData['image_data'][1]['code'] and $orderedData['image_data'][1]['caption'] etc. 

function remove_image($orderedData, $imageNo){ 
    unset($orderedData['image_data'][$imageNo]); 
    $newArray = array_values($orderedData['image_data']); 

    // Now I need to shift the keys of $newArray so that $newArray[0]['code'] becomes $newArray[1]['code'] etc. 

} 
+0

當我開始編程我最恨的就是數從0開始不是從1,隨着時間的推移我也就習慣了,發現它的一些常識。即使在數據庫中的記錄存儲順序中,也有從0開始計數的許多好處。 – Nazariy 2010-12-12 18:00:52

回答

0

你可以做這樣的事情:

$i = 0; 
$new_array = array(); 
foreach($orderedData as $value) 
{ 
    ++$i; 
    $new_array[$i] = $value; 
} 
+0

啊,一個比較簡單的方法,不知道爲什麼我沒有想到!實際上,我已經將第三行更改爲foreach($ orderedData ['image_data']爲$ value),因爲它僅僅是我之後的那些值,但是這完美地工作!非常感謝! – Inigo 2010-12-12 18:19:29

0

這應該適合你的目的,添加到該函數的底部:

array_unshift($newArray, array()); 
unset($newArray[0]); 
+0

我喜歡這個,但似乎有點破解添加一些東西,然後刪除它,所以我要與styu上面的答案,但謝謝! – Inigo 2010-12-12 18:21:02

+0

https://stackoverflow.com/questions/2172937/php-remove-element-from-array-with-reordering/47865489#47865489 – 2017-12-18 09:43:18