PHP数字数组顺序

编程入门 行业动态 更新时间:2024-10-09 18:26:14
本文介绍了PHP数字数组顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个数组,想要创建一个新的数字数组。这看起来像这样:

I have an array and want to create a new numeric array. This looks like this:

$created_old = explode("_", $result[$i]["created"]); $created_new = array(); $created_new[0] = $created_old[2]; $created_new[1] = $created_old[0]; $created_new[2] = $created_old[1]; $created_new[3] = ""; $created_new[4] = rtrim(explode(":", $created_old[3])[2], ")"); //Get name from the database $created_new[3] = $name; $created = implode("_", $created_new);

此版本运行正常,但前一个版本缺少一行,因此代码如下:

This version works just fine, but the previous was missing one line, so the code would be this:

$created_old = explode("_", $result[$i]["created"]); $created_new = array(); $created_new[0] = $created_old[2]; $created_new[1] = $created_old[0]; $created_new[2] = $created_old[1]; //$created_new[3] = ""; - I am missing $created_new[4] = rtrim(explode(":", $created_old[3])[2], ")"); //Get name from the database $created_new[3] = $name; $created = implode("_", $created_new);

在第二个代码中,字符串 $ created 是错误的顺序。索引4和3被切换。如果它是一个关联数组,我会理解这一点,但因为它是一个数值数组,我假设索引在数字上增加并且如此订购。由于我有一个工作版本,我不需要帮助来修复此代码,而是理解代码行为的原因...

In the second code the string $created is in the wrong order. The index 4 and 3 are switched. If it would be an associative array I would understand this but as it is an numeric array I assume the indices to increase numerically and beeing ordered like this. As I have a working version I do not need help to fix this code but rather understand why the code behaves as it does...

最好的问候 JRsz

Best regards JRsz

推荐答案

所有PHP数组都是关联的。口语中没有数字阵所期望的东西。密钥可以是字符串或数字,也无关紧要。密钥仍按其插入顺序排序,并且从不按其值隐式排序。我不会对这种行为感到惊讶:

All PHP arrays are associative. There's no such thing as a "numeric array" expect in colloquial speech. A key can be either a string or a number, it doesn't matter. Keys are still ordered by their order of insertion and never implicitly ordered by their value. You would not be surprised by this behaviour I assume:

$arr['a'] = 1; $arr['c'] = 3; $arr['b'] = 2; // ['a' => 1, 'c' => 3, 'b' => 2]

完全相同的机制在你的数字数组中起作用。

The exact same mechanics are at work in your "numeric array".

如果您想对按键进行排序,则需要使用 ksort 。

If you want to sort your keys, you need to do so explicitly using ksort.

更多推荐

PHP数字数组顺序

本文发布于:2023-11-30 18:22:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651048.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   顺序   数字   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!