将 New/Update $key 和 $value 添加到 WordPress 中的数组

Add New/Update $key and $value to an Array in WordPress

我正在尝试 add/update 一个新的 $key 和 $value 到现有数组。

表单输入:

<input name="flyer_packages[55][price][custom_price]" value="1000">

当前数组:

Array (
      [55] => Array (
                    [date] => 10 October 
                    [pricing_option] => true 
                    [price] => Array (
                                     [price_amount] => 3 000     
                                     [price_descriptor] => None 

添加新元的WP功能:

if (!empty ($_POST['flyer_packages'])) {
     $flyer_packages = get_post_meta($pid, 'flyer_packages', true);
     foreach ($flyer_packages as $flyer_package) {
         foreach ($flyer_package[price] as $key => $value) {
             update_post_meta( $pid, 'flyer_packages' , $_POST['flyer_packages']);
         }
     }
}

预期结果:

Array (
      [55] => Array (
                    [date] => 10 October
                    [pricing_option] => true 
                    [price] => Array (
                                     [price_amount] => 3 000     
                                     [price_descriptor] => None
                                     [custom_price] => 1 000 

实际结果:

Array (
      [55] => Array (
                    [price] => Array (
                                     [custom_price] => 1 000

如您所见,结果添加了新的键和值,但删除了数组中的所有其他键和值。

有哪位大侠指点一下,不胜感激。

发生这种情况是因为您要替换值,您必须先合并数组

   if (!empty ($_POST['flyer_packages'])) {
      $flyer_packages = get_post_meta($pid, 'flyer_packages', true);
      $new_value = $_POST['flyer_packages'];
      custom_keys_recursive($new_value, $flyer_packages);   
      update_post_meta( $pid, 'flyer_packages', $flyer_packages);   
   }  

   function custom_keys_recursive($value, &$array) {
     foreach ($value as $k=>$v) {
        if (is_array($v)) {
          custom_keys_recursive($v, $array[$k]);
        } else {
          $array[$k] = $v;
        }
     }
   }