Php 组织元素的顺序并推送子数组的总数

Php 组织元素的顺序并推送子数组的总数,php,Php,我想重新组织元素的顺序,并将子数组的总数推送到主数组。我想返回如下结果: $base_arr = Array ( 1 => Array ( 0 => 1, 1 => 2, 2 => 5, 3 => 5 ), 3 => Array ( 0 => 1,

我想重新组织元素的顺序,并将子数组的总数推送到主数组。我想返回如下结果:

 $base_arr =   Array
  (
      1 => Array
          (
          0 => 1,
          1 => 2,
          2 => 5,
          3 => 5
          ),
      3 => Array
          (
          0 => 1,
          1 => 2
          ),
      7 => Array
          (
          0 => 1,
          1 => 4
          )
   );

谁能帮我,谢谢。

这应该会给你想要的结果:

 $new_arr =   Array(
     0 => 1,
     1 => 2,
     2 => 5,
     3 => 5,
     4 =>13, //this is the total 1+2+5+5 = 13
     5 => 1,
     6 => 2,
     7 => 3,//this is the total 1+2 = 3
     8 => 1,
     9 => 4,
     10 =>5 //this is the total 1+4 = 5

   );

这将为您提供所需的结果:

 $new_arr =   Array(
     0 => 1,
     1 => 2,
     2 => 5,
     3 => 5,
     4 =>13, //this is the total 1+2+5+5 = 13
     5 => 1,
     6 => 2,
     7 => 3,//this is the total 1+2 = 3
     8 => 1,
     9 => 4,
     10 =>5 //this is the total 1+4 = 5

   );
使用数组函数:

$new_arr = array();
foreach($base_arr as $base)
{
    $count = 0; //Reset in begin of the loop (with 0)
    foreach($base as $child) 
    {
        $count += $child; //Count the values
        $new_arr[] = $child;
    }
    $new_arr[] = $count; //Put totale in the array
}

print_r($new_arr);
使用数组函数:

$new_arr = array();
foreach($base_arr as $base)
{
    $count = 0; //Reset in begin of the loop (with 0)
    foreach($base as $child) 
    {
        $count += $child; //Count the values
        $new_arr[] = $child;
    }
    $new_arr[] = $count; //Put totale in the array
}

print_r($new_arr);

在PHP 5.3中尝试闭包的好机会:

$new=array();
foreach ($base_arr as $bb) {
  $new=array_merge($new, $bb);
  array_push($new, array_sum($bb));
}

在PHP 5.3中尝试闭包的好机会:

$new=array();
foreach ($base_arr as $bb) {
  $new=array_merge($new, $bb);
  array_push($new, array_sum($bb));
}

您将如何使用该新阵列?这样做的话,如果你修改$new_arr,比如说添加一个新元素,那么跟踪每个基本数组的总数和元素会很麻烦。您不能使用assoc数组来标记$new\u arr吗?如果你不知道$new_arr[4]是不是一个总数,那么你可以访问$new_arr[1]['total']的总数。我同意AJweb。但是如果你对每个totale使用$new_arr['totale'],你就不知道你想要哪一个了:第一个totale有13个,第二个totale有3个,第三个totale有5个新数组我将用于paganation$new_arr,$show_peru页面定义了$show_.@Ajweb,Tricker,你们两个都知道吗?thanksHow你会使用这个新数组吗?这样做的话,如果你修改$new_arr,比如说添加一个新元素,那么跟踪每个基本数组的总数和元素会很麻烦。您不能使用assoc数组来标记$new\u arr吗?如果你不知道$new_arr[4]是不是一个总数,那么你可以访问$new_arr[1]['total']的总数。我同意AJweb。但是如果你对每个totale使用$new_arr['totale'],你就不知道你想要哪一个了:第一个totale有13个,第二个totale有3个,第三个totale有5个新数组我将用于paganation$new_arr,$show_per_page定义的页面。@Ajweb,Tricker,你们两个都知道吗?谢谢