Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php字符串名称作为数组中的变量_Php_Arrays_String_Variable Variables - Fatal编程技术网

php字符串名称作为数组中的变量

php字符串名称作为数组中的变量,php,arrays,string,variable-variables,Php,Arrays,String,Variable Variables,如何将数组中的字符串定义为新数组, 如何用php编写代码 $column = array("id","name","value"); 假设从mysql中找到了3行 想结果是这样吗 $id[0] = "1"; $id[1] = "6"; $id[2] = "10"; $name[0] = "a"; $name[1] = "b"; $name[2] = "c"; $value[0] = "bat"; $value[1] = "rat"; $value[2] = "cat"; 我想从$colu

如何将数组中的字符串定义为新数组, 如何用php编写代码

$column = array("id","name","value");
假设从mysql中找到了3行

想结果是这样吗

$id[0] = "1";
$id[1] = "6";
$id[2] = "10";

$name[0] = "a";
$name[1] = "b";
$name[2] = "c";

$value[0] = "bat";
$value[1] = "rat";
$value[2] = "cat";
我想从
$column
数组中获取字符串,并将其定义为新数组

如何编码? 或者,如果我的问题是愚蠢的,我的建议


谢谢。

我不明白你为什么要这样对数据建模,你要求的是调试方面的伤害。有一些“变量”可用于定义此变量,或使用$GLOBALS动态构建全局变量:

$somevar = "hello"
$$somevar[0] = "first index";  // creates $hello[0]

$GLOBALS[$somevar][0] = "first index"; // creates $hello[0] in global scope
试一试

或者你可以简单地这样做

$id = array();
$name = array();
$value = array();

foreach ( $results as $r ){
    $id[] = $r['id']; // or $r[0];
    $name[] = $r['name'];
    $value[] = $r['value'];
}

希望这是你所问的

< P>这是相当危险的,因为它可能会覆盖你认为在代码中安全的变量。您要查找的是
摘录

$result = array();

while ($row = mysql_fetch_array($result)) 
  foreach ($column as $i => $c) 
    $result[$c][] = $row[$i];

extract($result);

因此,如果
$result
数组('a'=>array(1,2),'b'=>array(3,4))
,那么最后一行定义变量
$a=array(1,2)
$b=array(3,4)
您不能直接使用变量进行此操作,而且无论如何也不应该使用变量。但你可以这样做:

foreach (mysql_fetch_something() as $row) {
    foreach ($row as $key=>$value) {
        $results[$key][] = $value;
    }
}

extract($results);

理想情况下,您可以跳过
提取
,并使用
$results['id'][1]
等。但如果您只提取()子函数中的嵌套数组,则局部变量作用域污染是可以接受的。

回答我在前面的问题:

$result = mysql_query($sql);
$num = mysql_num_rows($result);
$i = 0;

if ($num > 0) {
  while ($row = mysql_fetch_assoc($result)) {
    foreach($row as $column_name => $column_value) {
      $temp_array[$column_name][$i] = $column_value;
    }
    $i++;
  }

  foreach ($temp_array as $name => $answer) {
    $$name = $answer;
  }
}

不需要数组或使用$\u GLOBALS,我认为创建基于另一个变量值命名的变量的最佳方法是使用花括号:

$variable_name="value";

${$variable_name}="3";

echo $value;

//Outputs 3
如果您对接收到的阵列更加具体,我可以给出一个更完整的解决方案,尽管我必须警告您,我从未使用过这种方法,这可能是一个坏主意的迹象

如果您想了解更多信息,这里有一个有用的链接:

$variable_name="value";

${$variable_name}="3";

echo $value;

//Outputs 3