将新/更新$ key和$ value添加到WordPress中的数组

时间:2018-10-25 08:49:07

标签: arrays wordpress associative-array

我正在尝试向现有数组添加/更新新的$ 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

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

任何人都可以提出建议,非常感谢。

1 个答案:

答案 0 :(得分:1)

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

   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;
        }
     }
   }