gpt4 book ai didi

重新排序数组的PHP函数

转载 作者:行者123 更新时间:2023-12-02 05:23:43 25 4
gpt4 key购买 nike

这是来自 paypal.com 的所有外部 JS 文件的示例数组:

Array
(
[src] => Array
(
[1] => https://www.paypalobjects.com/WEBSCR-590-20090814-1/js/lib/min/global.js
[2] => https://www.paypalobjects.com/WEBSCR-590-20090814-1/js/tns/mid.js
[8] => https://www.paypalobjects.com/WEBSCR-590-20090814-1/js/opinionlab/oo_engine.js
[11] => https://www.paypalobjects.com/WEBSCR-590-20090814-1/js/iconix.js
[12] => https://www.paypalobjects.com/WEBSCR-590-20090814-1/js/pageBlockingUnsafeBrowsers.js
[13] => https://www.paypalobjects.com/js/tns/min/bid.js
[15] => https://www.paypalobjects.com/WEBSCR-590-20090814-1/js/pp_naturalsearch.js
[17] => https://www.paypalobjects.com/WEBSCR-590-20090814-1/js/site_catalyst/pp_jscode_080706.js
)

[size] => Array
(
[1] => 0.273
[2] => 0.266
[8] => 0.279
[11] => 0.265
[12] => 0.285
[13] => 0.248
[15] => 0.275
[17] => 0.289
)

)

是否有 PHP 的内置函数,或可以将此数组重新排序的自定义函数(也不会对性能造成重大影响):

Array
(
[src] => Array
(
[1] => https://www.paypalobjects.com/WEBSCR-590-20090814-1/js/lib/min/global.js
[2] => https://www.paypalobjects.com/WEBSCR-590-20090814-1/js/tns/mid.js
[3] => https://www.paypalobjects.com/WEBSCR-590-20090814-1/js/opinionlab/oo_engine.js
[4] => https://www.paypalobjects.com/WEBSCR-590-20090814-1/js/iconix.js
[5] => https://www.paypalobjects.com/WEBSCR-590-20090814-1/js/pageBlockingUnsafeBrowsers.js
[6] => https://www.paypalobjects.com/js/tns/min/bid.js
[7] => https://www.paypalobjects.com/WEBSCR-590-20090814-1/js/pp_naturalsearch.js
[8] => https://www.paypalobjects.com/WEBSCR-590-20090814-1/js/site_catalyst/pp_jscode_080706.js
)

[size] => Array
(
[1] => 0.273
[2] => 0.266
[3] => 0.279
[4] => 0.265
[5] => 0.285
[6] => 0.248
[7] => 0.275
[8] => 0.289
)

)

最佳答案

这个函数应该可以工作,而且尽可能简单。

function reindex_array($src) {
$dest = array();

foreach ($array as $key => $value) {
if (is_array($value)) {
foreach ($value as $dest_val) {
$dest[$key][] = $dest_val;
}
}
}

return $dest;
}

按照 Henrik's answer 中的建议使用 array_values()

function reindex_array($src) {
$dest = array();

foreach ($array as $key => $value) {
if (is_array($value)) {
$dest[$key] = array_values($value);
}
}

return $dest;
}

这将使数组索引从 0 开始。如果你想要基于 1 的索引,那么使用这个:

function reindex_array($src) {
$dest = array();

foreach ($array as $key => $value) {
if (is_array($value)) {
$count = 1;

foreach ($value as $dest_val) {
$dest[$key][$count] = $dest_val;
$count++;
}
}
}

return $dest;
}

关于重新排序数组的PHP函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1316916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com