如何将数组切成两个数组

时间:2012-10-04 05:42:17

标签: php arrays

我有一个需要分成两部分的数组(见下文):      [items] =>阵列

    (

        [product] => Humbucker
        [product_price] => 12
        [model] => Single Humbucker
        [model_price] => 12
        [guitarbrands] => fdfdfdf
        [guitarbrands_price] => 23
        [neckfretboard] => 33
        [neckfretboard_price] => 22
        [guitarmodels] => fdfdsf
        [guitarmodels_price] => 22

    )

我想要这个数组

   [items] => Array
    (

        [product] => array(
                            [product] => Humbucker
                            [product_price] => 12
                          )
        [model] =>   array( 
                            [model] => Single Humbucker
                            [model_price] => 12
                          )

        [guitarbrands] =>array(
                            [guitarmodels] => fdfdsf
                            [guitarbrands_price] => 23
                           )

    )

2 个答案:

答案 0 :(得分:0)

我通常保留一般用途的功能,例如:

function preg_grep_keys( $pattern, $input, $flags = 0 )
{
    $keys = preg_grep( $pattern, array_keys( $input ), $flags );
    $vals = array();
    foreach ( $keys as $key )
    {
        $vals[$key] = $input[$key];
    }
    return $vals;
}

所以在你的情况下,你会做这样的事情

 $outoupt=array(
        'product'=> preg_grep_keys('/^product/', $input),
         'model'=> preg_grep_keys('/^model/', $input),
         'product'=> preg_grep_keys('/^guitar/', $input)
          );        

希望这可能会有所帮助

答案 1 :(得分:0)

$result = array('items' => array());

foreach ($array as $key => $value) {
    if (strpos($key, '_') !== false) {
        continue;
    }
    $result['items'][$key] = array(
        $key           => $value,
        "{$key}_price" => $array["{$key}_price"]
    );
}