简体   繁体   English

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

[英]Populating PHP list() with values in an array

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()中的变量:

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. 我从API获取数据的CSV,第一行是列名,随后的每一行是数据。 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. 因此,我用所需的列名构建了一个数组,运行一些检查以确保CSV确实包含我需要的所有列。 Once thats done, the code looks somewhat like this (which is executed on a foreach() for each row of data in the CSV): 一旦完成,代码看起来将如下所示(对于CSV中的每一行数据,都在foreach()上执行):

//$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. 因为我已经有一个列名数组,所以我可以节省一些时间在列表函数中使用THAT,而不是显式地输入每个变量名。

The data is cleaned and sanitised elsewhere. 数据在其他地方被清理和消毒。

Cheers, 干杯,

Mike 麦克风

I want to have the elements in that array appear as the variables in my list(): 我想让该数组中的元素显示为list()中的变量:

i think there is your problem in understanding. 我认为您的理解存在问题。 list() does not create a new list structure or variable, it can only be used to assign many variables at once: list()不会创建新的列表结构或变量,它只能用于一次分配多个变量:

$arr = array(1, 2, 3);
list($first, $second, $third) = $arr;
// $first = 1, $second = 2, $third = 3

see http://php.net/list for more information. 有关更多信息,请参见http://php.net/list

you are probably looking for an associative array . 您可能正在寻找一个关联数组 you can create it with the following code: 您可以使用以下代码创建它:

$arr = array('first' => 1, 'second' => 2, 'third' => 3);
// $arr['first'] = 1, …

If some rows in your input file are missing columns, you can't really know which one is missing. 如果输入文件中的某些行缺少列,则您无法真正知道缺少哪一行。 Counting the number of values and aborting or jumping to next row when less than expected should be enough. 计算值的数量并在少于预期的数量时中止或跳至下一行就足够了。

... unless you set the rule that last columns are optional. ...,除非您设置最后一列为可选的规则。 I'll elaborate on this. 我会详细说明。

Your code sample is far for complete but it seems that your problem is that you are using arrays everywhere except when matching column names to cell values. 您的代码示例远远不够完整,但是似乎您的问题是,除了将列名与单元格值匹配之外,您在各处都使用了数组。 Use arrays as well: you don't need individual variables and they only make it harder. 也要使用数组:您不需要单个变量,它们只会使难度增加。 This is one of the possible approaches, not necessarily the best one but (I hope) clear enough: 这是一种可能的方法,不一定是最好的方法,但是(我希望)足够清楚:

<?php

$required_columns = array('name', 'age', 'height');
$input_data = array(
    array('John', 33, 169),
    array('Bill', 40, 180),
    array('Ashley', 21, 155),
    array('Vincent', 13), // Incomplete record
    array('Michael', 55, 182),
);
$output = array();

foreach($input_data as $row_index => $row){
    foreach($required_columns as $col_index => $column_name){
        if( isset($row[$col_index]) ){
            $output[$row_index][$column_name] = $row[$col_index];
        }
    }
}

print_r($output);

?>

I've used $row_index and $col_index for simplicity. 为了简单起见,我使用了$ row_index和$ col_index。

Original answer, for historical purposes only ;-) 原始答案,仅出于历史目的;-)

I can't really understand your specs but PHP features variable variables : 我不太了解您的规格,但是PHP具有可变变量

<?php

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

foreach($arr as $i){
    $$i = $i;
}

?>

Now your script has these variables available: $foo, $bar... It's quite useless and potentially dangerous but it does what you seem to need. 现在,您的脚本具有以下可用变量:$ foo,$ bar ...这虽然没什么用,并且可能很危险,但是它确实满足了您的需要。

why not immediatly call the vars like 为什么不立即将vars称为

$arr['foo']

or 要么

$arr[0]

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. 使用变量变量,如Alvaro所述。

$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. 编写帮助程序功能以使代码更清晰。

If you want to extract the elements of $data into the current context, you can do that with extract . 如果要将$data的元素提取到当前上下文中,可以使用extract You might find it useful to call array_intersect_key first to pare down $data to the elements that you want to extract. 您可能会发现首先调用array_intersect_key将$ data缩减为要提取的元素很有用。

May be try like this : 可以这样尝试:

$arr = array('foo', 'bar', 'bash', 'monkey', 'badger');
$data = "$".implode(",", $arr);
echo str_replace(",", ",$", $data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM