2017-07-02 169 views
1

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

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 
    ) 

然后,我将需要caegory和岗位阵列中的WP查询

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

请加上预期结果 –

+0

哪一个是你的愿望输出?第二个?? –

+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

+0

让我测试一下吧兄弟! –

+0

弗雷恩!我想我让你感到困惑。首先,我会希望获得索引“category_input”的子数组。 –

+0

通过使用'$ main_arr [category_input]'你可以得到非常多的子阵列 –