Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何将值从一个数组追加到另一个数组_Php_Arrays - Fatal编程技术网

Php 如何将值从一个数组追加到另一个数组

Php 如何将值从一个数组追加到另一个数组,php,arrays,Php,Arrays,我有两个结构如下的数组 array 'main' => array 'firstYearStudents' => array 0 => '10' 1 => '12' 'secondYearStudents' => array 0 => '8' 1 => '9' 'programCode' => array 0 => '03.0

我有两个结构如下的数组

array
  'main' => array
     'firstYearStudents' => array
        0 => '10'
        1 => '12'

     'secondYearStudents' => array
        0 => '8'
        1 => '9'

     'programCode' => array
        0 => '03.02.01'
        1 => '03.01.01'

     'educationProgramName' => array
        0 => 'Mathematics'
        1 => 'Physics'

  'total' => array
     'totalFirstYear' => '22'
     'totalSecondYear' => '17'
     'programCode' => '-'
     'totalEducationProgramName' => 'Total Directions'

那么所需的结构应该是这样的

array
  'main' => array
     'firstYearStudents' => array
        0 => '10'
        1 => '12'
        2 => '22'

     'secondYearStudents' => array
        0 => '8'
        1 => '9'
        2 => '17'

     'programCode' => array
        0 => '03.02.01'
        1 => '03.01.01'
        2 => '-'

     'educationProgramName' => array
        0 => 'Mathematics'
        1 => 'Physics'
        2 => 'Total Directions'

我尝试了以下操作,但我获得了命名密钥,因此无法访问这些密钥

$i = 0;
foreach ($studentsEditInfo['main'] as $values) {
    $studentsEditInfo['main'] = array_merge($values, $studentsEditInfo['total'][$i]);
    $i++;
}
我不知道如何在我的“主”数组的foreach循环中访问我的“total”数组的索引。

如果你的“total”数组的顺序总是这样,你可以在添加值之前将总数转换成数字数组

像这样

$arr["total" ] = ["a" => 1,"b" => 2, "c" => 3];
$arrNumeric = [];
foreach ($arr["total"] as $item) {
  $arrNumeric []= $item;
}
之后,您只需要运行此代码来添加数组值

$i = 0;
foreach ($studentsEditInfo['main'] as $values) {
    $values []= $arrNumeric[$i];
    $i++;
}

顺便说一句,我没有对此进行测试。

我不知道您想要什么,但是,您可以使用$studentsEditInfo['main'],因为$key=>$循环中的值可能会对您有所帮助,如果您不总是知道密钥名称,则必须按顺序匹配它们。这是否回答了您的问题?标题中的“如何将值从一个数组附加到另一个数组”。。。我不知道如何在我的“主”数组的foreach循环中访问我的“total”数组的索引?要获取一个值或合并两个数组?请对您的代码进行解释,并说明它解决问题的原因。发布普通代码对其他人没有帮助。
$total = [];
foreach ($studentsEditInfo['main']['total'] as $keyTotal => $valueTotal) {
            $total[] = $valueTotal;
        }

        unset($studentsEditInfo['main']['total']);

        $index = 0;
        foreach ($studentsEditInfo['main'] as $keyMain => $valueMain) {
            $studentsEditInfo['main'][$keyMain][] = $total[$index];
            if ($index > count($studentsEditInfo['main'])) {
                continue;
            }
            $index++;
        }