如何使用可变变量访问数组中的指定键

How do I access a specifing key in an array using variable variables

我的问题太曲折了,我什至不知道如何开始解释它。

假设我有几个关联数组(并不总是相同的数组:有时我有产品数组,有时我有市场数组,有时我有段数组,等等)。 $values 是我总是得到的唯一数组!

$values = array ("0" => "1", "4" => "2", "5" => "3");
$products = array ("0" => "1", "1" => "1", "2" => "2", "3" => "1", "4" => "2", "5" => "3");
$markets =  array ("0" => "1",  "3" => "1", "4" => "2", "5" => "3");
...

我想用我得到的每个数组的值构建一个数组,这些值与键匹配。 像

$myArray = array ("0" => array ( "values" => "1", "products" => "1", "markets" => "1"),
                  "1" => array ( "products" => "1"),
                  "2" => array ( "products" => "2"),
                  "3" => array ( "products" => "1", "markets" => "1"),
                  "4" => array ( "values" => "2", "products" => "2", "markets" => 2),
                ...);

我试过这样的事情:

        switch ($_POST["cpv_type"]) {
            case "pClass":
                $keyValue = $_POST["cpv_type"];
                $objKey   = "this->productClasses";
                break;

            case "pMarket":
                $keyValue = $_POST["cpv_type"];
                $objKey   = "this->markets";
                break;

            case "pSegment":
                $keyValue = $_POST["cpv_type"];
                $objKey   = "this->productSegments";
                break;

            case "pType":
                $keyValue = $_POST["cpv_type"];
                $objKey   = "this->productTypes";
                break;

            default:
                $keyValue = "products";
                $objKey = "this->products";
                break;
        }

然后我做一个foreach cicle:

    // all values must be floats
    if(!empty($this->value)){
        foreach ($this->value as $key => &$curVal){
            // if no value has been entered, exclude it and also associated product from validation
            if (strlen(trim($curVal)) == 0) {
                unset($this->value[$key]);
                unset($this->products[$key]);
            } else {
                                        // This validates my variable 
                $curVal =   TMS::checkVar($curVal, "dec", $_SESSION["dico"]->_VALUE_, 100, false);


                                        // Store the value on existing array, associating "hoppValue" to the right key entry!
                $logDetail[$keyValue][${$objKey}[$key]]["hoppValue"] = $curVal;
            }
        }
    }

我的问题出在变量变量上: 如何访问,例如 $this->productTypes[5] 使用变量语法? $$objKey${$objKey}${$objKey}[$key]${$objKey[$key]}$$objKey[$key]

的所有 var_dumps 我得到 "null"

感谢您的帮助!

您可以简单地获取数组以防 $objKey = $this->productClasses 并用作 $objKey[$key]。您可以将 $objKey 替换为 $arrayClasses 或类似的代码以便更好地理解代码。

p.s。对不起我的英语。