-3

我试图在加入两个 sql 表后检索记录。结果数组如下:

Array
(
[0] => Array
    (
        [optionId] => 150
        [price] => 2.00
        [name] => 1 Ice
        [languageId] => 4
    )

[1] => Array
    (
        [optionId] => 150
        [price] => 2.00
        [name] => Ek Burph
        [languageId] => 1
    )

[2] => Array
    (
        [optionId] => 151
        [price] => 5.00
        [name] => 2 Ice
        [languageId] => 4
    )

[3] => Array
    (
        [optionId] => 151
        [price] => 5.00
        [name] => Do Burph
        [languageId] => 1
    )

)

我想将此数组转换为以下格式,以便在我的应用程序中轻松解析。

Array
(
[0] => Array
    (
        [optionId] => 150
        [price] => 2.00
        [languages]=>array(
           [0]=>array(
              [name] => 1 Ice
              [languageId] => 4
           )
           [1]=>array(
              [name] => Ek Burph
              [languageId] => 1
           )
        )
    )

[1] => Array
    (
        [optionId] => 151
        [price] => 5.00
        [languages]=>array(
           [0]=>array(
              [name] => 2 Ice
              [languageId] => 4
           )
           [1]=>array(
              [name] => Do Burph
              [languageId] => 1
           )
        )
    )

)

IE。我需要在 PHP 中对属于同一 optionId 的项目进行分组,但无法弄清楚如何。请帮忙。

4

1 回答 1

1

自己搞定了:

    $array2 = array();
    $f = 0;
    if($array1){
        foreach($array1 as $option){
            $i = 0;
            foreach($array2 as $option2){
                if($option2['optionId'] == $option['optionId']){
                    $array2[$i]['language'][] = array('name'=>$option['name'],'languageId'=>$option['languageId']) ;
                    $f = 1;
                }
                $i++;
            }

            if(!$f){
                $array2[$i]['optionId'] = $option['optionId'];
                $array2[$i]['price'] = $option['price'];
                $array2[$i]['language'][] = array('name'=>$option['name'],'languageId'=>$option['languageId']);
            }

            $f = 0;
        }
    }
于 2012-05-31T12:15:49.497 回答