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

发布于 2024-10-07 02:55:06 字数 844 浏览 0 评论 0原文

我的问题与此类似 -

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁月流歌 2024-10-14 02:55:06

你可以这样做:

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

You can do something like this:

$i = 0;
$new_array = array();
foreach($orderedData as $value)
{
    ++$i;
    $new_array[$i] = $value;
}
空城仅有旧梦在 2024-10-14 02:55:06

这应该适合您的目的,添加到该函数的底部:

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

This should suit your purpose, add to the bottom of that function:

array_unshift($newArray, array());
unset($newArray[0]);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文