0

I am trying to unset/remove then replace/update a single value from a post meta field, but my code for array_push() and unset() are removing all of the values from each array.

Here are the two halves of the code I am currently using.

First, to find and remove the old value:

 $ID = $_GET["post_id"];
 $old = $entry["85"];
 $old_meta = array();
 $old_meta = get_post_meta($old,'_website',false);

 if(in_array($ID, $old_meta[current][items])){ 
       unset($old_meta[current][items][$ID]); 
  }

 update_post_meta($old,'_website',$old_meta);

Second to append the new value to the appropriate location:

$port = $entry["24"];
$new_meta = array();
$new_meta = get_post_meta($port,'_website',false);
$new_meta[content][items] = array();
array_push($new_meta[content][items],$ID);
update_post_meta($port,'_website',$new_meta);

It works to unset and insert the correct value, but any other values that were there (for both updating or unsetting) in the meta[current][items] array are removed.

Before running any functions the array looks like this: pastie.org/8112933

After I run array_push it looks like this: pastie.org/8112956

After unset it looks like this: pastie.org/8112974

Paul Farry
  • 4,730
  • 2
  • 35
  • 61
Kyle
  • 422
  • 1
  • 6
  • 10

1 Answers1

0

in_array checks to see if an element in array has a value equal to that value, not a key. So you would need to do something like this:

if(in_array($ID, $old_meta['current']['items'])){
    foreach($old_meta['current']['items'] as $key => $val) {
        if($val == $ID) {
            unset($old_meta['current']['items'][$key]);
        }
    }
}

If you need to check for a key not a value just replace in_array() with array_key_exists() and keep your current code.

Pitchinnate
  • 7,517
  • 1
  • 20
  • 37