如何在PHP中将数组特殊键更改为数字

时间:2016-12-10 14:45:02

标签: php arrays

我使用以下代码删除数组,但我认为存在问题

How do I delete a specific array in php

 array(2) {
  [7]=>array(3) {
    ["title"]=>string(3) "ads"
    ["number"]=>int(3)
    [1]=>array(2) {
      ["address-image"]=>string(63) "http://localhost/wordpress/wp-content/uploads/2017/08/120-3.jpg"
      ["expire"]=>string(10) "2017/03/10"
    }
    [2]=>array(2) {
      ["address-image"]=>string(63) "http://localhost/wordpress/wp-content/uploads/2016/09/240.jpg"
      ["expire"]=>string(10) "2016/10/20"
    }
    [3]=>array(2) {
      ["address-image"]=>string(63) "http://localhost/wordpress/wp-content/uploads/2016/10/300.jpg"
      ["expire"]=>string(10) "2016/12/28"
    }
  }
  ["_multiwidget"]=>int(1)
}

跑步后:

array(2) {
  [7]=>array(2) {
    ["title"]=>string(3) "ads"
    ["number"]=>int(2)
    [1]=>array(2) {
      ["address-image"]=>string(63) "http://localhost/wordpress/wp-content/uploads/2017/08/120-3.jpg"
      ["expire"]=>string(10) "2017/03/10"
    }
    [3]=>array(2) {
      ["address-image"]=>string(63) "http://localhost/wordpress/wp-content/uploads/2016/10/300.jpg"
      ["expire"]=>string(10) "2016/12/28"
    }
  }
  ["_multiwidget"]=>int(1)
}

但我希望稍后更改如下(从[3]到[2]的关键更改):

array(2) {
  [7]=>array(2) {
    ["title"]=>string(3) "ads"
    ["number"]=>int(2)
    [1]=>array(2) {
      ["address-image"]=>string(63) "http://localhost/wordpress/wp-content/uploads/2017/08/120-3.jpg"
      ["expire"]=>string(10) "2017/03/10"
    }
    [2]=>array(2) {
      ["address-image"]=>string(63) "http://localhost/wordpress/wp-content/uploads/2016/10/300.jpg"
      ["expire"]=>string(10) "2016/12/28"
    }
  }
  ["_multiwidget"]=>int(1)
}

抱歉,我的英语不是很好

谢谢

3 个答案:

答案 0 :(得分:0)

删除后使用array_merge()功能

unset($data[7]["number"][2]);
$data[7]["number"] = array_merge($data[7]["number"]);

答案 1 :(得分:0)

使用array_values创建新数组: 例如:

$arr = array(1, 2, 3);

unset($arr[0]);
$arr = array_values($arr);

print_r($arr);
//Array ( [0] => 2 [1] => 3 )

答案 2 :(得分:0)

试试这个。假设php -r "readfile('https://getcomposer.org/installer');" | php mv composer.phar /usr/local/bin/composer 正在存储您的数组,并希望交换数组键2和3。

$a
交换后

然后取消设置要删除的元素。