0

我想获取一个数组,使用 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"}. 目前,${"$value_category"}foreach 循环中的 in 打印出正确的值/数组,而$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 数组都有自己的变量名,这样我就可以随时随地打印出来。

4

1 回答 1

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";

?>
于 2013-11-04T03:47:08.780 回答