【问题标题】:Delete key with its values in a multidimensional array in WordPress在WordPress的多维数组中删除键及其值
【发布时间】:2014-02-22 07:04:42
【问题描述】:

我需要能够从插入到 WordPress 选项表中的数组中删除自定义键,这是我使用 print_r 作为回报的数组:

Array (
[customkeyone] => Array (
   [itemname] => 'name'
   [sortorder] => 1
   [date] => 1393042529
   [target] => 1
   )
[customkeytwo] => Array (
   [itemname] => 'nametwo'
   [sortorder] => 1
   [date] => 1393042525
   [target] => 1
   )
[customkeythree] => Array (
   [itemname] => 'namethree'
   [sortorder] => 1
   [date] => 1393042522
   [target] => 1
   )
)

我尝试了不同的方法并且已经接近但无法实际删除/取消设置整个自定义键本身。假设我想取消设置“customkeytwo”,我需要一种方法来传递这个自定义 id 并将其删除:

处理程序示例:

if (isset($_GET['delete'])) {

    //ID in this case is "customkeytwo" 
    if ($_REQUEST['id'] != ''){

                $id = $_REQUEST['id'];
                $myoptions = get_option('myoptions'); 

                //some method to unset the custom key with $id

                //update with new results
                update_option('myoptions', $myoptions); 

这就是我希望删除后的结果:

Array (
[customkeyone] => Array (
   [itemname] => 'name'
   [sortorder] => 1
   [date] => 1393042529
   [target] => 1
   )
[customkeythree] => Array (
   [itemname] => 'namethree'
   [sortorder] => 1
   [date] => 1393042522
   [target] => 1
   ) 
)

【问题讨论】:

    标签: php arrays wordpress multidimensional-array


    【解决方案1】:

    为什么不直接使用unset

    unset($myoptions[$_REQUEST['id']]); // will remove "customkeytwo"
    print_r($myoptions);
    

    【讨论】:

    • 你调试了吗? var_dump($options) & var_dump($_REQUEST['id']) 给了你什么?
    • var_dump($_REQUEST['id']) ----> string(12) "customkeytwo"
    • 我可以删除键值,但不能删除键本身
    • 对不起,这实际上是正确的,经过一些良好的休息后,我能够看到更新选项行的小错误,但它现在正在工作并且这个方法是正确的
    • 你能分享你的“小错误”以及你做了什么来解决它吗?我有同样的问题,我试图取消设置数组,然后用 update_option 重新提交它,但是当我这样做时,我得到一个空条目
    猜你喜欢
    • 1970-01-01
    • 2015-11-07
    • 2013-11-05
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-01
    • 2014-11-17
    相关资源
    最近更新 更多