Zubair Mushtaq
Zubair Mushtaq

Reputation: 323

php get sub array from an array

here is an array and I want to extract "category_input" as sub array. This sub array contains "cat_id" and "post-titles". Then I will want to insert the posts into WordPress DB under each category. is. cat_20 will have posts named as post-in-cat-20 and so on.

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
        )

)

Expected Results

extracted array will be as

    [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
    )

Then, I will need to make caegory and posts array to use in wp query

    [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
    )

Upvotes: 1

Views: 199

Answers (1)

Murad Hasan
Murad Hasan

Reputation: 9583

As you want to update the portion of your array- take a look at the given parts.

The array from the main array by $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;
    }
}

Look at the complete example: https://3v4l.org/JI9U7

Now you can put the $out_arr again to the $main_arr.

Upvotes: 2

Related Questions