如何拆分数组并将每个值存储在localstorage中

时间:2017-10-25 06:12:44

标签: javascript php arrays

我有如下的数组,

Array
(
    [0] => http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png
    [1] => http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png
    [2] => http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911571.png
)

我想拆分上面的数组,每个键值必须存储在local 'front'=> array[0],'back'=>array[1],'side'=>array[0]这样的localStorage中。

如何实现这一目标。 ?

2 个答案:

答案 0 :(得分:0)

  1. 如果你的数组在 JAVASCRIPT 中,你可以直接访问数组元素,所以你可以直接调用localStorage函数......

    var yourArray = [
        'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png',
        'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png',
        'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911571.png'
    ];
    
    localStorage.setItem('front',yourArray[0]);
    localStorage.setItem('back',yourArray[1]);
    localStorage.setItem('side',yourArray[2]);
    
  2. 如果您的数组位于 PHP 中,则必须添加<script>元素...

    <?php
    $yourarray = array(
        "http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png",
        "http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png",
        "http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911571.png"
    );
    ?>
    
    <script>
      localStorage.setItem('front','<?=$yourarray[0]?>');
      localStorage.setItem('back','<?=$yourarray[1]?>');
      localStorage.setItem('side','<?=$yourarray[2]?>');
    </script>
    

答案 1 :(得分:0)

你可以有单独的脚本(test.php)并且json out如下

<?php

$arr1 = array(
    0 => 'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png',
    1 => 'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911570.png',
    2 => 'http://192.168.1.156/dutees_dev/image/catalog/tmprgbimages/1508911571.png'
);

$arr2 = array('front'=>'', 'back'=>'', 'side'=>'');


// assign values from array 1 to array 2
$arr2['front'] = $arr1[0];
$arr2['back'] = $arr1[1];
$arr2['side'] = $arr1[2];


echo json_encode($arr2);

然后从javascript您可以按如下方式访问此对象并将其存储在本地存储

<script>

            $(document).ready(function () {
                $.get("test.php", function (data, status) {

                    var out = JSON.parse(data);

                    // Store in local storage
                    localStorage.setItem("frontElem", out.front);
                    localStorage.setItem("backElem", out.back);
                    localStorage.setItem("sideElem", out.side);

                    var side = localStorage.getItem("sideElem", out.side);
                    console.log(side)

                });
            });

        </script>