php从数组中获取子数组

时间:2017-07-02 06:04:53

标签: php arrays wordpress

这是一个数组,我想将“category_input”提取为子数组。该子数组包含“cat_id”和“post-titles”。然后我想将帖子插入到每个类别下的WordPress DB中。是。 cat_20将有一个名为post-in-cat-20的帖子,依此类推。

Array
(
    [post_type] => post
    [post_status] => publish
    [content_texarea] => 
    [category_input] => Array
        (
            [0] => cat_20
            [1] => post-in-cat-20
            [2] => post-in-cat-20
            [3] => post-in-cat-20
            [4] => cat_19
            [5] => post-in-cat-19
            [6] => post-in-cat-19
            [7] => post-in-cat-19
            [8] => post-in-cat-19
            [9] => cat_2
            [10] => post-in-cat-2
            [11] => post-in-cat-2
            [12] => post-in-cat-2
        )

)

预期结果

提取的数组将为

    [category_input] => Array
    (
        [0] => cat_20
        [1] => post-in-cat-20
        [2] => post-in-cat-20
        [3] => post-in-cat-20
        [4] => cat_19
        [5] => post-in-cat-19
        [6] => post-in-cat-19
        [7] => post-in-cat-19
        [8] => post-in-cat-19
        [9] => cat_2
        [10] => post-in-cat-2
        [11] => post-in-cat-2
        [12] => post-in-cat-2
    )

然后,我需要在wp查询中使用caegory和posts数组

    [category_input] => Array
    (
        [cat_20] => Array
            [1] => post-in-cat-20
            [2] => post-in-cat-20
            [3] => post-in-cat-20
        [cat_19] => Array
            [5] => post-in-cat-19
            [6] => post-in-cat-19
            [7] => post-in-cat-19
            [8] => post-in-cat-19
        [cat_2] => Array
            [10] => post-in-cat-2
            [11] => post-in-cat-2
            [12] => post-in-cat-2
    )

1 个答案:

答案 0 :(得分:2)

如果您想更新阵列的一部分,请查看给定的部分。

$main_arr[category_input];

中主阵列中的数组
foreach($category_input as $val){
    $part = explode('_', $val);
    if(isset($part[0]) && $part[0] == 'cat'){
        $out_arr[$val] = array();
        $key = $val;
    }else{
        $out_arr[$key][] = $val;
    }
}

查看完整示例:https://3v4l.org/JI9U7

现在,您可以将$out_arr再次添加到$main_arr