-1

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

    (

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

    )
4

2 回答 2

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"]
    );
}
于 2012-10-04T06:16:21.297 回答
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)
          );        

希望这可能会有所帮助

于 2012-10-04T06:08:04.583 回答