Traversal of javascript-php nested arrays

Source: Internet
Author: User
The problem is as follows:

现有一个多级嵌套数组,如果用 foreach 遍历,那遍历的也只是数组的一个拷贝,无法修改原始数组的值,除非$array[$key]这样,但是层级多了这样也是不方便的。

Actual situation:

现在用多级数组储存着一些没有规律的数据,因为数据太杂太乱我没有用数据库而是直接采用json文件来存储,比较类似数组。现在要改动数据,很可能就是直接改动数组最底层的数据,我采用的是将查询的键发送到PHP后台,然后foreach遍历找到最终的键值。

Solving:

如果继续用遍历数组的方法来修改,请问有没有什么更好的解决方案。如果各位对于存储无规律数据有见解,求指教,我也觉得采用json文件来存储数据不太可靠。

Reply content:

The problem is as follows:

现有一个多级嵌套数组,如果用 foreach 遍历,那遍历的也只是数组的一个拷贝,无法修改原始数组的值,除非$array[$key]这样,但是层级多了这样也是不方便的。

Actual situation:

现在用多级数组储存着一些没有规律的数据,因为数据太杂太乱我没有用数据库而是直接采用json文件来存储,比较类似数组。现在要改动数据,很可能就是直接改动数组最底层的数据,我采用的是将查询的键发送到PHP后台,然后foreach遍历找到最终的键值。

Solving:

如果继续用遍历数组的方法来修改,请问有没有什么更好的解决方案。如果各位对于存储无规律数据有见解,求指教,我也觉得采用json文件来存储数据不太可靠。

What do you mean by traversing the modified value or something? Put a code for your reference:

/**     * 使用点分割形式的键名设置多维数组中的值     *     * @param array $array     * @param string $key     * @param mixed $value     * @return array     */    public static function dotSet(array & $array, $key, $value)    {        if (null === $key) {            // 如果键为null,直接替代数组            return $array = $value;        }        $keys = explode('.', $key);        while (count($keys) > 1) {            $key = array_shift($keys);            if (!isset($array[$key]) || !is_array($array[$key])) {                $array[$key] = [];            }            $array = & $array[$key];        }        $array[array_shift($keys)] = $value;        return $array;    }

dotSet($array, "n.l.m.o", $value)You can change $array['n']['l']['m']['o'] the value by using the

I saw you as soon as I came in.

A reference can be used in foreach

$arr = array(array(1, 2, 3), array(2, 3, 4), array(3, 4, 5));foreach($arr as &$v){    foreach($v as &$vv)    {        $vv = ++$vv;    }}print_r($arr);
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.