php - 循环遍历 foreach php 中的列

标签 php arrays for-loop

我试图在 foreach 循环中循环遍历一行的列,为每一行创建一个新数组。

$e = 1;
$columns = array('colname1', 'colname2', 'colname3', 'colname4','colname5');
foreach ($variable as $row) {
  for ($i=1; $i < 5;)
  {
      $new_array[$i] = (
      array(
          'id' => NULL,
          'order_line_id' => $order_line_id,
          'size' => $e,
          'qty' => $row->$columns[$i] //error is here
          )
      );
      $i++;
      $blank_detail[$i] = (
      array(
          'id' => NULL,
          'order_line_id' => $order_line_id,
          'size' => $e."-",
          'qty' => $row->$columns[$i] //error is here
          )
      );
      $e++;
  };
}

是否有更好/更有效的方法来执行此操作,或者这只是一个语法错误?

最佳答案

您正在使用数组作为 variable variable ,所以你需要更改这一行:

'qty' => $row->$columns[$i]

'qty' => $row->{$columns[$i]}

PHP7 和 PHP5 之间在处理间接变量方面也有很多变化,check it out .

Indirect access to variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the previous mix of special cases. The table below shows how the order of evaluation has changed.

因此,如果您在 PHP5 中使用此语法 'qty' => $row->$columns[$i] 这将意味着您的 PHP 将解释您的代码并获取 $i 索引来自 $column 数组,而在 PHP7 中,解释器将解释您的代码并从 $row- 获取 $i 索引>$columns 数组会抛出错误,因为:
1 - $columns 是一个数组,您正在尝试访问非法索引类型。
2 - 即使 $columns 是有效的索引类型( string ),该索引也没有第 $i 个元素。


而且我很确定您可以使用 array_combine而不是执行两个嵌套循环

关于php - 循环遍历 foreach php 中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46885548/

相关文章:

c++ - 基于范围的for循环对性能有好处吗?

php - INSERT ... ON DUPLICATE KEY UPDATE - 不更新特定字段?

php - 在php中将特定的mysql表导出到excel

javascript - PHP (AJAX) 的对象数组

javascript - 数组中的元素自动更新

ios - 如何在 Swift 中创建一个空数组?

django - Django 模板中的嵌套循环

Python - 在 for 循环中增加范围下限

php - .htaccess 动态清洁 URL

php - 如何解码 JSON 字符串