我的代码删除键如下:
<?php
$photoList = array(
array(
'id' => 1,
'name' => 'chelsea.jpg'
),
array(
'id' => 2,
'name' => 'mu.jpg'
),
array(
'id' => 3,
'name' => 'city.jpg'
)
);
if(count($photoList) > 1) {
$id = 1;
foreach($photoList as $key => $value) {
if($value['id'] == $id)
unset($photoList[$key]);
}
}
echo '<pre>';print_r($photoList);echo '</pre>';
?>
如果执行代码,结果如下:
Array
(
[1] => Array
(
[id] => 2
[name] => mu.jpg
)
[2] => Array
(
[id] => 3
[name] => city.jpg
)
)
我希望值重新更新。所以id从1开始,键从0开始,如下所示:
Array
(
[0] => Array
(
[id] => 1
[name] => mu.jpg
)
[1] => Array
(
[id] => 2
[name] => city.jpg
)
)
我该怎么做?请帮帮我,有什么不对?谢谢
您可以保留一个标志$delete
并使用它来记住是否已完成删除,然后更改值,如果它是真的。
if(count($photoList) > 1) {
$id = 1;
$delete = false;
foreach($photoList as $key => &$value) { // notice the & to make it by reference (editable)
if($value['id'] == $id && $delete == false){
$delete = true;
unset($photoList[$key]);
}Else if($delete == true){
$value["id"] = $id;
$id++; // update id for next value in array
}
}
}
$photoList= array_values($photoList);
没有参考:
if(count($photoList) > 1) {
$id = 1;
$delete = false;
foreach($photoList as $key => $value) {
if($value['id'] == $id && $delete == false){
$delete = true;
unset($photoList[$key]);
}Else if($delete == true){
$photoList[$key]["id"] = $id;
$id++;
}
}
}
$photoList= array_values($photoList);
试试这个..
<?php
$photoList = array(
array(
'id' => 1,
'name' => 'chelsea.jpg'
),
array(
'id' => 2,
'name' => 'mu.jpg'
),
array(
'id' => 3,
'name' => 'city.jpg'
)
);
$newphotolist = [];
$counter_id = 0;
if(count($photoList) > 1) {
$id = 1;
foreach($photoList as $key => $value) {
if($value['id'] != $id){
$counter_id++;
$arr = array('id' => $counter_id, 'name' => $value['name']);
$newphotolist[] = $arr;
}
}
}
echo '<pre>';print_r($newphotoList);echo '</pre>';
?>
$photoList = array(
array(
'id' => 1,
'name' => 'chelsea.jpg'
),
array(
'id' => 2,
'name' => 'mu.jpg'
),
array(
'id' => 3,
'name' => 'city.jpg'
)
);
if(count($photoList) > 1) {
$id = 1;
foreach($photoList as $key => $value) {
if($value['id'] == $id)
unset($photoList[$key]);
}
}
在工作结束时,先重新排序密钥。
$photoList = array_values($photolist);
然后,重新排序你的身份。
foreach($photoList as $key=>$val) {
$photoList[$key]['id'] = $key+1;
}
<?php
$photoList = array(
array(
'id' => 1,
'name' => 'chelsea.jpg'
),
array(
'id' => 2,
'name' => 'mu.jpg'
),
array(
'id' => 3,
'name' => 'city.jpg'
)
);
if(count($photoList) > 1) {
$id = 1; $intStartId = 1;
foreach($photoList as $key => &$value) {
if($value['id'] == $id)
unset($photoList[$key]);
else {
$value['id'] = $intStartId;
++ $intStartId;
}
}
}
$photoList = array_merge(array(), $photoList);
echo '<pre>';print_r($photoList);echo '</pre>';