我想获取一个数组,使用foreach循环将其循环,并通过类发送每个数组值以从数据库获取数据。这是我目前使用的代码:
foreach ($unique_category as $key => $value)
{
$category = $value;
$value = new database;
$value->SetMysqli($mysqli);
$value->SetCategory($category);
$value->query_category();
${"$value_category"} = $value->multi_dim_array();
print_r(${"$value_category"});
echo "<br /><br />";
}
print_r($unique_category[0]."_category");
我希望变量$unique_category[0]."_category"
为${"$value_category"}
。
目前,foreach循环中的${"$value_category"}
打印出正确的值/数组,而$unique_category[0]."_category"
只打印person_category(person是该数组中的第一个值)。
如何让$unique_category[0]."_category"
打印与${"$value_category"}
相同的内容?
谢谢
编辑:
foreach循环正在创建一个类似于Array ( [0] => Array ( [0] => Home [1] => 9.8 ) [1] => Array ( [0] => Penny [1] => 8.2 ))
的多维数组我希望能够在foreach循环外打印出这个数组,每个md数组都有自己的变量名,所以我可以打印它们随时随地都可以出去。
答案 0 :(得分:0)
<?php
$unique_category_list = array('foo', 'bar', 'baz');
foreach ($unique_category_list as $key => $value)
{
$category = $value;
$value_category = $value."_".$category;
$unique_category = $unique_category_list[$key]."_category";
$unique_category = ${"$value_category"} = $key;
print_r($unique_category_list[$key]."_category");
echo "\n\n";
}
?>
输出:
foo_category
bar_category
baz_category
<?php
// note that $unique_category is now $unique_category_list && $value is now $category
foreach ($unique_category_list as $key => $category)
{
$database = new Database();
$database->setMysqli($mysqli);
$database->setCategory($category);
$database->query_category();
// http://www.php.net/manual/en/language.oop5.magic.php#object.tostring
// this will invoke the `__toString()` of your $database object...
// ... unless you meant like this
// $value_category = $category."_".$category;
$value_category = $database."_".$category;
$unique_category = $unique_category_list[$key]."_category";
// http://stackoverflow.com/questions/2201335/dynamically-create-php-object-based-on-string
// http://stackoverflow.com/questions/11422661/php-parser-braces-around-variables
// http://php.net/manual/en/language.expressions.php
// // http://php.net/manual/en/language.variables.variable.php
// 'I want the variable $unique_category[0]."_category" to be ${"$value_category"}.'
$unique_category = ${"$value_category"} = $database->multi_dim_array();
}
print_r($unique_category_list[0]."_category");
echo "<br><br>\n\n";
?>