2017-07-02 190 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]'你可以得到非常多的子陣列 –