如何在foreach迭代中修改多维数组的子元素 [英] How to modify subelement of multidimensional array in foreach iteration

查看:60
本文介绍了如何在foreach迭代中修改多维数组的子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图修改多维数组的每个数组元素中第一个子元素的内容,但是,如果我通过引用传递所述元素,则会出现错误&".不是预期的.我是否需要放弃foreach($ arr as list())语法并恢复为标准的循环和使用计数器变量进行访问?

I am attempting to modify the contents of the first subelement in each array element of a multidimensional array, however, if I pass said element by reference I get an error that "&" is not expected. Do I need to ditch the foreach ($arr as list ()) syntax and revert to a standard for loop and access with a counter variable?

foreach ($transactions as list(&$student, &$tyID)) {

    $query = "SELECT $column
              FROM student
              WHERE stUserID=$student";

    if ($stmt = mysqli_prepare($link, $query)) {
        mysqli_stmt_execute($stmt);

        mysqli_stmt_bind_result($stmt, $userHID);

        while (mysqli_stmt_fetch($stmt)) {
            $student = $userHID;
            $tyID = $transType[$tyID];
        }

        mysqli_stmt_close($stmt);
    }
}

更新了代码,实际上我需要修改事务数组中每个数组的前两个子元素.

Updated code, I actually need to modify the first two subelements of each array in the transactions array.

推荐答案

为什么不能以这种方式呢?假设键与列表变量相同

Why can't you do it in this way? Assumed the keys are same as the list variables

foreach ($transactions as &$transaction) {

    $query = "SELECT {$column}
              FROM student
              WHERE stUserID={$transaction['student']}";

    if ($stmt = mysqli_prepare($link, $query)) {
        mysqli_stmt_execute($stmt);

        mysqli_stmt_bind_result($stmt, $userHID);

        while (mysqli_stmt_fetch($stmt)) {
            $transaction['student'] = $userHID;
            $transaction['tyID'] = $transType[$transaction['tyID']];
        }

        mysqli_stmt_close($stmt);
    }
}

这篇关于如何在foreach迭代中修改多维数组的子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆