如何更新多维Post Meta中的单值?

时间:2016-07-24 作者:Ramesh Pardhi

Post元数据中有一些值存储为多维数组。我想更新他们的一些数据。

以下是使用<?php the_meta(); ?>

voter: a:1:{s:5:"voter";a:5:
     {s:7:"post_id";s:6:"219585";s:8:"voter_id";s:4:"1540";s:8:"voter_ip";s:13:"182.4
     8.238.86";s:9:"author_id";s:4:"1540";s:4:"vote";s:1:"1";}}, 

     a:1:{s:5:"voter";a:5:          
     {s:7:"post_id";s:6:"219585";s:8:"voter_id";s:3:"832";s:8:"voter_ip";s:13:"182.48
     .238.86";s:9:"author_id";s:4:"1540";s:4:"vote";s:2:"-1";}}, 

     a:1:{s:5:"voter";a:5:
     {s:7:"post_id";s:6:"219585";s:8:"voter_id";s:2:"10";s:8:"voter_ip";s:13:"182.48.
     238.86";s:9:"author_id";s:4:"1540";s:4:"vote";s:1:"1";}}
现在我想更新votevoter_ip 哪里user_id is 832或1540。我试过使用update_post_meta() 但它正在更新一切。

那么,如何更新多维数组中存储的单个值的后置元呢?

Update:

数组使用the-meta()

voter: a:1:{s:5:"voter";a:5:{s:7:"post_id";s:6:"219585";s:8:"voter_id";s:3:"832";s:8:"voter_ip";s:13:"182.48.238.86";s:9:"author_id";s:4:"1540";s:4:"vote";s:1:"1";}}, 
 a:1:{s:5:"voter";a:5:{s:7:"post_id";s:6:"219585";s:8:"voter_id";s:4:"1540";s:8:"voter_ip";s:13:"182.48.238.86";s:9:"author_id";s:4:"1540";s:4:"vote";s:2:"-1";}}, , , 
a:1:{s:5:"voter";a:5:{s:7:"post_id";s:6:"219585";s:8:"voter_id";s:3:"832";s:8:"voter_ip";s:13:"182.48.238.86";s:9:"author_id";s:4:"1540";s:4:"vote";s:1:"1";}}, 
a:1:{s:5:"voter";a:5:{s:7:"post_id";s:6:"219585";s:8:"voter_id";s:4:"1540";s:8:"voter_ip";s:13:"182.48.238.86";s:9:"author_id";s:4:"1540";s:4:"vote";s:2:"-1";}}
数组使用print_r()

Array( [0] => Array ( [voter] => Array ( [post_id] => 219585 [voter_id] =>
832 [voter_ip] => 182.48.238.86 [author_id] => 1540 [vote] => 1 ) ) [1] =>
Array ( [voter] => Array ( [post_id] => 219585 [voter_id] => 1540 [voter_ip]
=> 182.48.238.86 [author_id] => 1540 [vote] => -1 ) ) [2] => [3] => [4] =>
Array ( [voter] => Array ( [post_id] => 219585 [voter_id] => 832 [voter_ip]
=> 182.48.238.86 [author_id] => 1540 [vote] => 1 ) ) [5] => Array ( [voter] 
=> Array ( [post_id] => 219585 [voter_id] => 1540 [voter_ip] => 
182.48.238.86 [author_id] => 1540 [vote] => -1 ) )) 

1 个回复
SO网友:majick

您可能需要取消序列化数据,以获取数组并在其中循环,因此:

$userid = 832; // or 1540
$votes = get_post_meta($postid,\'voter\');
$votes = maybe_unserialize($votes);

if (is_array($votes)) {
    // votes is the array, key is numeric index, vote is subarray
    foreach ($votes as $key => $vote) {
         // subarray values are in another array with key \'voter\'
         if ($vote[\'voter\'][\'voter_id\'] == $userid) {
             $votes[$key][\'voter\'][\'vote\'] = $newvote;
             $votes[$key][\'voter\'][\'voter_ip\'] = $newvoterip;
         }                 
    }
    update_post_meta($postid,\'voter\',$voter);
}