【问题标题】:Using an array value to retrieve from another array使用数组值从另一个数组中检索
【发布时间】:2015-09-21 08:55:58
【问题描述】:

我创建了一个数组,其中一个是 php 用来显示从 sqlite3 检索到的记录中的字段的字符串。

我的问题是......它没有。

数组已定义,“1”为第一个数据库字段,“2”为第二个数据库字段:

编辑:我已将问题重新定义为脚本,以便您可以看到整个事情:

//If I have an array (simulating a record retrieved from database):
$record = array(
    name => 'Joe',
    comments => 'Good Bloke',
    );

//then I define an array to reference it:
$fields = array( 
    1 => array(
    'db_index' => 'name',
    'db_type' => 'TEXT',
    'display' => '$record["name"]',
    'form_label' => 'Name',
    ),
    2 => array(
    'db_index' => 'comments',
    'db_type' => 'TEXT',
    'display' => '$record["comments"]',
    'form_label' => 'Comments',
    ),  
);  

//If I use the lines:
print "expected output:\n";
print " Name = " . $record["name"] ."\n";
print " Comments = " . $record["comments"] ."\n";

//I display the results from the $record array correctly.
//However if I try & use the fields array with something like:
Print "Output using Array values\n";
foreach($GLOBALS["fields"] as $field)
    {
        $label = $field['form_label'];
        $it = $field['display'];    
        $line = "\"$label = \" . $it .\"\n\"";
        print $line;
    }

输出:

Expected output:
 Name = Joe
 Comments = Good Bloke
Output using Array values:
 Name = $record["name"] 
 Comments = $record["comments"] 

【问题讨论】:

  • 是的,“echo”也可以用来代替“print”,但不会改变输出。
  • $record["name"] 有一些值,否则将按原样打印?
  • 不太明白你想问什么。

标签: php arrays database multidimensional-array


【解决方案1】:

不要从字符串中调用变量。只需连接它:

foreach($GLOBALS["fields"] as $field){
    $label = $field['form_label'];
    $it = $field['display'];

    eval("$it = ".$it);
    $line = $label." = ".$it."\n";
    print $line;
}

嗯,它看起来怎么样?

【讨论】:

  • 是的,一个更好的构造字符串的方法,但它仍然产生相同的结果:Name = $record["name"]Comments = $record["cmets"]
  • 您已经改变了输出字符串的构造方式,但您还没有解决主要问题。您的解决方案仍然产生相同的错误输出 Name = $record["name"] Comments = $record["cmets"] 不是预期的输出。
猜你喜欢
  • 2022-11-10
  • 1970-01-01
  • 2023-01-30
  • 1970-01-01
  • 1970-01-01
  • 2020-04-06
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
相关资源
最近更新 更多