How to change the value of an specific associative array in PHP?

跟風遠走 提交于 2019-12-11 02:33:47

问题


I've a dynamically generated very huge array called $test_package_data. For your understanding I'm giving below the contents of array $test_package_data.

Now what I want to achieve is convert the value of an array key

$test_duration = ConvertTimeStampToTimeFormate($some_key['test_duration']);

In short I want to update the value of a key ['test_duration'] eveywhere in the array. But not understanding how should I loop over the array and achieve the desired result.


回答1:


You can use array_walk_recursive() and adjust a value if the key matches 'test_duration':

array_walk_recursive($test_package_data, function(&$value, $key) {
    if ($key == 'test_duration') {
        $value = ConvertTimeStampToTimeFormate($value);
    }
});



回答2:


You can loop over $test_package_data['category_detail'][0]['test_detail']. So code will be something like,

foreach($test_package_data['category_detail'][0]['test_detail'] as $key => $value){
    $test_package_data['category_detail'][0]['test_detail'][$key]['test_duration'] = 
    ConvertTimeStampToTimeFormate($value['test_duration']]);
}



回答3:


Although array_walk_recursive is the best, but this should also work.

function changValue($dataArray) {
  foreach($dataArray as $key=>$val) {
   if(is_array($val)) {
     return changValue($val);
   } else {
     if ($key == 'test_duration') {
        $value = ConvertTimeStampToTimeFormate($value);
    }
   }
  }
}

changeValue($yourArray);


来源:https://stackoverflow.com/questions/21455644/how-to-change-the-value-of-an-specific-associative-array-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!