在Php中取消设置多维数组值,重新排序和返回?

时间:2010-12-12 17:53:27

标签: php multidimensional-array

我的问题类似于这个问题 -

PHP | Remove element from array with reordering?

...除了当我返回有序数组时,我希望键从1开始。但是,我的数组是多维的。通过阅读关于array_values函数的PhP手册中的注释,我理解键发生了一些奇怪的事情(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.

}

2 个答案:

答案 0 :(得分:0)

您可以这样做:

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

答案 1 :(得分:0)

这应该适合您的目的,添加到该功能的底部:

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