首页 > 解决方案 > 如何更新多维数组中的后元单值?

问题描述

基本上,我正在为 WooCommerce 产品页面创建一个自定义投票系统,用户将在其中选择单选选项并单击提交按钮进行投票。

每个投票项目可以有多个项目,每个项目有 3 个数据字段。所有数据都保存在帖子的元值中。

我如何为 ajax 动作处理程序编写 PHP 函数以更新多维后元数组中的单个值。在我的代码中,它不会更新,只是将新值保存到所有字段而不是我投票的字段。

$polls = get_post_meta($post_id,'polls',true);

转储数据$polls

array(3) {
  [0] => array(3) {
    ["title"] => string(15) "This is Title 1" 
    ["color_code"] => string(7) " "40"
  } [2] => array(3) {
    ["title"] => string(15) "This is Title 2"
    ["color_code"] => string(7) "#8224e3" 
    ["vote_number"] => string(2) "30"
  } [3] => array(3) {
    ["title"] => string(15) "This is Title 3" 
    ["color_code"] => string(7) "#eeee22" 
    ["vote_number"] => string(2)"50"
  }
}

前端

在此处输入图像描述

后端 在此处输入图像描述 民意调查摘录以投票形式显示

<form id="poll_form" method="post" action="">
<input id="post_id_number" type="hidden" name="post_id" value="<?php echo $post_id;?>">
    <ul>
    <?php 
    $title_array_data =  explode(',', $title_array);
    $color_array_data =  explode(',', $color_array);
    $vote_array_data =  explode(',', $vote_array);

    foreach ($title_array_data as $key => $value) { ?>
      <li>
          <input id="poll-vote-<?php echo $key;?>" name="polls[<?php echo $key;?>][vote_number]" type="hidden" value="<?php echo $vote_array_data[$key];?>" class="poll-item"/>
          <input id="poll-item-<?php echo $key;?>" name="polls[<?php echo $key;?>][radio]" type="radio" value="1" class="poll-item"/>
          <label id="pollitemlabel" for="poll-item-<?php echo $key;?>" style="color:<?php echo $color_array_data[$key] ;?>"><?php echo $value;?> </label>
      </li>
    <?php 
    }
    ?>
    <li class="submitbutton"><input type="submit" class="submit-vote" value="Vote"></li>
    </ul>
</form>

这就是 HTML 表单标记的样子

    <form id="thebomb_poll_form" method="post" action="">
    <input id="post_id_number" type="hidden" name="post_id" value="10255" />
    <ul>
        <li>
            <input id="poll-vote-0" name="polls[0][vote_number]" type="hidden" value="40" class="poll-item" />
            <input id="poll-item-0" name="polls[0][radio]" type="radio" value="1" class="poll-item" />
            <label id="pollitemlabel" for="poll-item-0" style="color: #81d742;">This is Title 1 </label>
        </li>
        <li>
            <input id="poll-vote-1" name="polls[1][vote_number]" type="hidden" value="30" class="poll-item" />
            <input id="poll-item-1" name="polls[1][radio]" type="radio" value="1" class="poll-item" />
            <label id="pollitemlabel" for="poll-item-1" style="color: #8224e3;">This is Title 2 </label>
        </li>
        <li>
            <input id="poll-vote-2" name="polls[2][vote_number]" type="hidden" value="50" class="poll-item" />
            <input id="poll-item-2" name="polls[2][radio]" type="radio" value="1" class="poll-item" />
            <label id="pollitemlabel" for="poll-item-2" style="color: #eeee22;">This is Title 3 </label>
        </li>
        <li class="submitbutton"><input type="submit" class="submit-vote" value="Vote" style="display: inline-block;" /></li>
    </ul>
</form>

ajax 动作处理程序的 PHP 函数

add_action( 'wp_ajax_nopriv_cast_vote', 'vote_cast_ajax' );
add_action( 'wp_ajax_cast_vote', 'vote_cast_ajax' );

function vote_cast_ajax(){

    $post_id = $_POST['post_id'];
    
    //getting meta value
    $polls = get_post_meta($post_id,'polls',true);
    
    $vote_data_array = array_column($polls, 'vote_number');
    $vote_array = implode(',', $vote_data_array);//used in shortcode    
    
    if (is_array($polls)) {
        // polls is the array, key is numeric index, vote is subarray
        foreach ($polls as $key => $vote) {
            $old_vote = $pols[$key]['vote_number'] ;
            $newvote += (int)$old_vote + 1 ;
            
            $vote[$key]['vote_number'] = $newvote;                               
        }
        update_post_meta($post_id,'polls',$vote);
    }
    

    wp_send_json_success( sprintf(
        __( 'Your vote has been cast successfully!.', 'ng-vote' )
    ) );
}

ajax请求处理的jquery代码

jQuery(document).ready(function ($) {
    $(".submitbutton .submit-vote").click(function (e) {
        // Prevent them from actually visiting the URL when clicking.
        e.preventDefault();

        // Add a little 'waiting' thingie to the cursor.
        $(document.body).css({ cursor: "wait" });
        var serialized = $("#thebomb_poll_form").serialize();
        // Start ajaxin'!
        $.ajax({
            type: "POST",
            url: ThebombAjax.ajaxurl,
            data: {
                action: "cast_vote", //calls TBAjax
                post_id: $("#post_id_number").val(),
            },
            dataType: "json",
            success: function (response) {
                // Add an alert with our success message.
                alert(response.data);

                // Change the cursor back to normal.
                $(document.body).css({ cursor: "default" });
            },
        }).fail(function (response) {
            // This stuff only happens if things fail miserably.
            $(document.body).css({ cursor: "default" });
            if (window.console && window.console.log) {
                console.log(response);
            }
        });
    });
});

标签: phpwordpress

解决方案


试试下面的代码。您必须将“$newvote”推送到“$polls[$key]['v​​ote_number']”

// polls is the array, key is numeric index, vote is subarray
foreach ($polls as $key => $vote) {
    $old_vote = $vote['vote_number'] ;
    $newvote += (int)$old_vote + 1 ;
    
    $polls[$key]['vote_number'] = $newvote;                               
}
update_post_meta($post_id,'polls',$polls);

推荐阅读