【问题标题】:Array with strings to integers字符串到整数的数组
【发布时间】:2018-01-02 08:58:51
【问题描述】:

我在使用数组(php、wordpress)时遇到了一些问题,如下所示:

array(2) {
  [0] => array(1) { [0]=> string(3) "416" }
  [1]=> array(1) { [0]=> string(4) "1591" }
}

如何将其转换为整数数组? 问题是值也是数组,而不是像这样的值:

array(2) {
      [0] =>  "416" ,
      [1]=> "1591" 
    }

我正在尝试使用 get_post_meta() 获取一些帖子的 ID。

这只是我的一段代码:

$course_product = array();
    foreach ($comment_ids as $comment_id) {
        $course_product[] = get_post_meta( intval($comment_id), '_llms_wc_product_id', true );
                    }

它给了我这个奇怪的数组:

array(2) {
  [0]=>
  array(1) {
    [0]=>
    string(3) "416"
  }
  [1]=>
  array(1) {
    [0]=>
    string(4) "1591"
  }
}

【问题讨论】:

    标签: php arrays wordpress type-conversion integer


    【解决方案1】:

    显然,您的元数据_llms_wc_product_id 本身就是一个数组。因此,通过附加 [0] 从中获取第一个值:

    get_post_meta( intval($comment_id), '_llms_wc_product_id', true )[0]
    

    【讨论】:

    • 非常感谢。你是对的,它是一个数组。我忘记了核心插件代码中有一些变化。现在我可以处理了。
    【解决方案2】:

    这个数组可以是这样的:

    array(2) {
      [0]=>
      array(1) {
        [0]=>
        string(3) "416"
      }
      [1]=>
      array(2) {
        [0]=>
        string(4) "1591"
        [1]=>
        string(3) "416"
      }
    }
    

    它不能更深,我只需要值,所以我正在使用:

    call_user_func_array('array_merge', $course_products);
    

    将其展平,然后它看起来像:

        array(3) { 
    [0]=> int(416) 
    [1]=> int(1591) 
    [2]=> int(416) 
    } 
    

    然后我就可以做我想做的了。

    大礼包。

    【讨论】:

    • 从 PHP 5.6 开始,您还可以编写 array_merge(...$course_products);
    猜你喜欢
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多