php 清空一个数组_PHP: array_replace - Manual

I got hit with a noob mistake. :)

When the function was called more than once, it threw a function redeclare error of course.  The enviroment I was coding in never called it more than once but I caught it in testing and here is the fully working revision.  A simple logical step was all that was needed.

With PHP 5.3 still unstable for Debian Lenny at this time and not knowing if array_replace would work with multi-dimensional arrays, I wrote my own.  Since this site has helped me so much, I felt the need to return the favor. :)

// Will take all data in second array and apply to first array leaving any non-corresponding values untouched and intactfunctionpolecat_array_replace( array &$array1, array &$array2) {// This sub function is the iterator that will loop back on itself ad infinitum till it runs out of array dimensionsif(!function_exists('tier_parse')){

functiontier_parse(array &$t_array1, array&$t_array2) {

foreach ($t_array2as$k2=>$v2) {

if (is_array($t_array2[$k2])) {tier_parse($t_array1[$k2],$t_array2[$k2]);

} else {$t_array1[$k2] =$t_array2[$k2];

}

}

return$t_array1;

}

}

foreach ($array2as$key=>$val) {

if (is_array($array2[$key])) {tier_parse($array1[$key],$array2[$key]);

} else {$array1[$key] =$array2[$key];

}

}

return$array1;

}?>

[I would also like to note] that if you want to add a single dimensional array to a multi, all you must do is pass the matching internal array key from the multi as the initial argument as such:

$array1= array("berries"=> array("strawberry"=> array("color"=>"red","food"=>"desserts"),"dewberry"= array("color"=>"dark violet","food"=>"pies"), );$array2= array("food"=>"wine");$array1["berries"]["dewberry"] =polecat_array_replace($array1["berries"]["dewberry"],$array2);?>

This is will replace the value for "food" for "dewberry" with "wine".

The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.

I hope this helps atleast one person for all that I've gained from this site.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值