在 Php 中取消设置多维数组值、重新排序并返回?
我的问题与此类似 -
...除了当我返回有序数组时,我希望键从 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.
}
My question is similar to this one-
PHP | Remove element from array with reordering?
...except that when I return the ordered array, I want the keys to start from 1. My array, however, is multidimensional. From reading the comments in the PhP manual about the array_values function, I understand that something weird happens with the keys (Carsten Milkau writes: 'Note that in a multidimensional array, each element may be identified by a sequence of keys, i.e. the keys that lead towards that element.')
This is baffling me, as it seems I can no longer simply use a foreach loop to iterate through the array and add 1 to the key value each time. I'd greatly appreciate some help with this, otherwise I'm going to have to implement some seriously ugly and verbose work-around... here is my code:
// $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.
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以这样做:
You can do something like this:
这应该适合您的目的,添加到该函数的底部:
This should suit your purpose, add to the bottom of that function: