简体   繁体   English

如何在 php 的 foreach 循环中取消设置键后重置数组索引?

[英]How to reset array index after unset key in foreach loop in php?

I am using unset to remove the particular object from the array with my conditions.我正在使用unset根据我的条件从阵列中删除特定的 object。 But after unset, I am getting an object rather than an array.但取消设置后,我得到的是 object 而不是数组。 I tried to use array_values to rearrange the index, but it's not working for me.我尝试使用array_values重新排列索引,但它对我不起作用。 Please help me to resolve this issue.请帮我解决这个问题。 Below is my code:下面是我的代码:

$empId = '100'; //just for example.
foreach($jsonData['data'] => $key as $value){
    if($value['emp_id'] == $empId){
        unset($jsonData['data][$key]);
    }
}
after loop code//
return $jsonData;

after unset data, it gives me an object.在未设置数据后,它给了我一个 object。 I tried with array_values , array_merge but it's not working for me.我尝试使用array_valuesarray_merge但它不适合我。 I tried to replace array_splice with unset , but it's not removing data.我试图用unset替换array_splice ,但它没有删除数据。

You have at least 2 serious syntax errors in your code.您的代码中至少有 2 个严重的语法错误。

This is what it should look like:这应该是这样的:

<?php

// Some dummy data
$empId = '100';
$jsonData = [];
$jsonData['data'] = [
    'key' => ['emp_id' => 'value'],
    'key2' => ['emp_id' => '100']
];

// Fixed foreach loop
foreach($jsonData['data'] as $key => $value) {
    if ( $value['emp_id'] == $empId ) {
        unset( $jsonData['data'][ $key ] );
    }
}

print_r($jsonData);

key emp_id is as string, not as index.键 emp_id 是字符串,而不是索引。 your code has unset emp_id.您的代码未设置 emp_id。 alternatively, you may use array_map function and then use array_values to reindex your array.或者,您可以使用 array_map function 然后使用 array_values 重新索引您的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM