PHP 数组循环和格式

PHP array loop and format

我对PHP很陌生,学得快但还不够快!我也在学习Laravel 5.1.

我正在尝试从 Eloquent 查询输出构建一个 HTML select 列表数组,格式正确,适用于表单生成器 (Form::select)。

我对 Eloquent 进行了以下调用以提取数据:

// Get list of States for address select
$states = State::all()->toArray();

它returns以下数组:

array:8 [▼
  0 => array:2 [▼
    "id" => "1"
    "state" => "ACT"
  ]
  1 => array:2 [▼
    "id" => "2"
    "state" => "NSW"
  ]
  ...
];

我想遍历它并生成以下输出:

array = [
   ''  => 'State',       <-- This is the default for the select list
   '1' => 'ACT',
   '2' => 'NSW',
   ...
];

我正在使用 Laravel 5.1,所以我在我的助手中使用了包含的 array_add() 函数。

我这样调用函数:

$states = create_select_list($states, 'State');

我接下来要格式化输出,以便为 Form::select 语句做好准备。我已经尝试了下面的代码(作为几次迭代的最后尝试!)但没有成功。

function create_select_list($data, $default)
{
    // Declare array and set up default select item
    $container = ['' => $default];

    // Loop through data entries and build select list array
    foreach($data as list($entry, list($key, $value))) {
        $container = array_add($container, $key, $value);
    }

    // Return the select list array
    return $container;
}

感谢所有帮助或建议!

您不需要在 foreach 循环中使用 list(),而是尝试:

foreach($data as $key => $value) {
    $container = array_add($container, $key, $value);
}

PHP documentation 很好地概述了 list() 的实际作用。

这个答案与循环修复无关。我认为之前的评论应该对您有所帮助。

只是另一个想法。对于这种情况,您可以尝试使用 array_map 而不是 foreach。

例如:

$states = ['' => 'State'];

array_map(function($item) use (&$states) {
    $states[$item['id']] = $item['state'];
}, State::all()->toArray());

循环如下:

foreach($data as $key => $keyArr ) {
    $container = array_add($container, $keyArr['id'], $keyArr['state']);
}