在PHP中的数组切片

时间:2014-11-04 13:42:46

标签: php arrays

我在数组下面: -

Array
(
    [adate] => 
    [ip_address] => 
    [atime] => 
    [self_fname] => hjhbhj
    [self_mi_nm] => bjb
    [self_last_nm] => bb
    [self_preferred_nm] => bbjhb
    [patient_is1] => 1
    [party_fname] => tgn
    [party_mname] => 
    [party_lname] => gn
    [party_str1] => 
    [party_apt1] => 
    [party_city1] => 
    [pt_str1] => 
    [pt_apt1] => 
    [pt_city1] => 
    [pt_state1] => 
    [pt_zip1] => 
)

我想将此数组分为2个数组,其中“party _”“pt _”。输出如下: -

Array
(
    [party_fname] => tgn
    [party_mname] => 
    [party_lname] => gn
    [party_str1] => 
    [party_apt1] => 
    [party_city1] =>  
)

Array
( 
    [pt_str1] => 
    [pt_apt1] => 
    [pt_city1] => 
    [pt_state1] => 
    [pt_zip1] => 
)

有人帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:4)

您可以使用foreach和strpos来获得所需的结果。

$arr = ORIGINAL DATA;
$arr1 = $arr2 = array();

foreach($arr as $key=>$value){
   if(strpos($key, 'party_') === 0){
       $arr1[$key] = $value;
       }
   else if(strpos($key, 'pt_') === 0){
       $arr2[$key] = $value;
       }
   }

这将输出两个数组,其中arr1的所有数据都带有以' party _'开头的键。和arr2的所有键都以' pt _'。

开头

答案 1 :(得分:0)

阅读本手册:http://php.net/manual/en/function.array-slice.php

如果您将原始数组称为$arrayMain,则代码为:

$arrayParty = array_slice($arrayMain, 8, 6, true);

$arrayPt = array_slice($arrayMain, 14, 5, true);