从主阵列中分离出一些不同的数据,并将每个数据再次合并到主阵列

时间:2018-01-21 13:13:15

标签: php arrays

以下数组是我所拥有的一个例子(请访问网址):

https://codepen.io/oghab98/pen/LeajRR

现在我想在cart_details键中分隔具有相同ID的数组,然后将主题与its parent array合并。

有人想要这样做是因为我应该将每个付款具有相同的ID,以便在cart_details中

如果有任何问题,或者您不了解我的代码,请在评论中提出。

1 个答案:

答案 0 :(得分:2)

实现此目的的一种方法是使用经典 foreach循环。

$array = [
  'id' => 2,
  'title' => 'world',
  'meta' => 25,
  'key' => 'text',
  'sub_arr' => [
      [
          'id' => 55
      ],
      [
          'id' => 55
      ],
      [
          'id' => 224
      ]
  ]
];

//Init $result array. Initially, this will be an associative array. using the `sub_arr` `id` as the key.
$result = array();

//Loop $array[ "sub_arr" ]
foreach ( $array[ "sub_arr" ] as $arr ) {

    //Check if $result[ $arr["id"] ] exist. eg: $result[55]
    if ( !isset( $result[ $arr["id"] ] ) ) {

        //Does not exist. So assign the the $array to $result[55]
        $result[ $arr["id"] ] = $array;

        //Overide the value of $result[55][""sub_arr""]
        $result[ $arr["id"] ][ "sub_arr" ] = [ $arr ];
    } else {

        //Already exist. So just push the new $arr to $result[55][""sub_arr""]
        $result[ $arr["id"] ][ "sub_arr" ][] = $arr;
    }
}

//Return all the values of an array. This will make the array from associative to basic numerical array
$result = array_values( $result );

这将导致:

Array
(
    [0] => Array
        (
            [id] => 2
            [title] => world
            [meta] => 25
            [key] => text
            [sub_arr] => Array
                (
                    [0] => Array
                        (
                            [id] => 55
                        )

                    [1] => Array
                        (
                            [id] => 55
                        )

                )

        )

    [1] => Array
        (
            [id] => 2
            [title] => world
            [meta] => 25
            [key] => text
            [sub_arr] => Array
                (
                    [0] => Array
                        (
                            [id] => 224
                        )

                )

        )

)