dsdvr06648 2010-04-20 12:15
浏览 30
已采纳

使用数组中的值填充PHP list()

I have an array:

$arr = array('foo', 'bar', 'bash', 'monkey', 'badger');

I want to have the elements in that array appear as the variables in my list():

list($foo, $bar, $bash, $monkey, $badger) = $data;

Without actually specifying the variables, I tried;

list(implode(",$", $arr)) = $data; and
list(extract($arr)) = $data;

But they don't work, I get:

Fatal error: Can't use function return value in write context

Does anyone have any idea whether this is possible?


UPDATE: more context:

I am getting a CSV of data from an API, the first row is column names, each subsequent row is data. I want to build an associative array that looks like this:

$data[0]['colname1'] = 'col1data';
$data[0]['colname2'] = 'col2data';
$data[0]['colname3'] = 'col3data';
$data[1]['colname1'] = 'col1data';
$data[1]['colname2'] = 'col2data';
$data[1]['colname3'] = 'col3data';

Before I do that, however, I want to make sure I have all the columns I need. So, I build an array with the column names I require, run some checks to ensure the CSV does contain all the columns I need. Once thats done, the code looks somewhat like this (which is executed on a foreach() for each row of data in the CSV):

//$data is an array of data WITHOUT string indexes
list(   $col1,
    $col2,
    $col3,
    ...
    $col14
 ) = $data;

foreach($colNames AS $name)
{
    $newData[$i][$name] = $$name;
}
// Increemnt
$i++;

As I already HAVE an array of column name, I though it would save some time to use THAT in the list function, instead of explicitly putting in each variable name.

The data is cleaned and sanitised elsewhere.

Cheers,

Mike

  • 写回答

6条回答 默认 最新

  • doutangguali32556 2010-04-20 14:27
    关注

    You are trying to use a language construct in a manner in which it's not meant to be used. Use variable variables as Alvaro mentioned.

    $arr = array('foo', 'bar', 'bash', 'monkey', 'badger');
    foreach ($arr as $index => $key) {
        $$key = $data[$index];
    }
    

    or

    $arr = array('foo', 'bar', 'bash', 'monkey', 'badger');
    $result = array();
    foreach ($arr as $index => $key) {
        $result[$key] = $data[$index];
    }
    extract($result);
    

    In short, do not use "list", use arrays and associated arrays. Write helper functions to make your code clearer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀