0

我有一个看起来像这样的数组。

Array
(

[0] => Array
    (
        [cartId] => 667
        [isPack] => 1
    )

[1] => Array
    (
        [cartId] => 668
        [isPack] => 1
    )

[2] => Array
    (
        [cartId] => 672
        [isPack] => 2
    )

[3] => Array
    (
        [cartId] => 673
        [isPack] => 2
    )

)

我想通过 isPack 元素创建一个数组,它应该看起来像这样。

Array (

[1] => Array
    (

       [0] => Array
            (
                [cartId] => 667
            )

        [1] => Array
            (
                [cartId] => 668
            )

    )
  [2] => Array
    (
        [0] => Array
            (
                [cartId] => 672
            )

        [1] => Array
            (
                [cartId] => 673
            )
    )  
 )

数组二将是两个数组,其中 isPack 将是数组键,其他信息将属于其子数组。

我怎样才能做到这一点?提前致谢 :)

4

2 回答 2

0

尝试:

$input  = array( /* your data*/ );
$output = array();

foreach ( $input as $data ) {
  $isPack = $data['isPack'];
  $cartId = $data['cartId'];

  if ( !isset($output[$isPack]) ) {
    $output[$isPack] = array();
  }
  $output[$isPack][] = array(
    'cartId' => $cartId
  );
}
于 2013-09-03T12:36:37.237 回答
0
  $new=array();
     $arr = array( array('cartId' => 667,'isPack' => 1),array('cartId' => 668,'isPack' => 1),array('cartId' => 672,'isPack' => 2),array('cartId' => 673,'isPack' => 2));
     for($i=0;$i<count($arr);$i++) {
          $l = $arr[$i]['isPack'];
     $new[$l][]['catid']= $arr[$i]['cartId'];
     }
     print_r($new);

和输出: -

Array
(
    [1] => Array
        (
            [0] => Array
                (
                    [catid] => 667
                )

            [1] => Array
                (
                    [catid] => 668
                )

        )

    [2] => Array
        (
            [0] => Array
                (
                    [catid] => 672
                )

            [1] => Array
                (
                    [catid] => 673
                )

        )

)
于 2013-09-03T12:43:39.337 回答