简体   繁体   中英

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. But after unset, I am getting an object rather than an array. I tried to use array_values to rearrange the index, but it's not working for me. 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. I tried with array_values , array_merge but it's not working for me. I tried to replace array_splice with unset , but it's not removing data.

You have at least 2 serious syntax errors in your code.

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. your code has unset emp_id. alternatively, you may use array_map function and then use array_values to reindex your array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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