开发者

Use string to store statement (or part of a statement), and then add it to the code

I use multidimensional arrays to store product attributes (well Virtuemart does, to be precise). When I tried to echo the sub-arrays value, if the sub-array did not exist PHP threw:

Fatal error: Cannot use string offset as an array

To get around this, I attempted to create a function to check on every array level if it is an actual array, and if it is empty (when trying on the whole thing at once such as: is_array($array['level1']['level2']['level3']), I got the same error if level1 or level2 are not actual arrays).

This is the function ($array contains the array to check, $array_levels is an array containing the names of the sub-arrays, in the order they should apper):

function check_md_array($array,$array_levels){
    i开发者_运维技巧f(is_array($array)){
        $dimension = null;  //This will store the dimensions string

        foreach($array_levels as $level){
            $dimension .= "['" . $level . "']"; //Add the current dimension to the dimensions string

            if(!is_array($array/* THE CONTENT OF $dimension SHOULD BE INSERTED HERE*/)){
                return false;
            }
        }           
        return true;
    }
}

How can I take the string contained in $dimensions, and insert it into the code, to be part of the statement?


Short of doing an eval, I don't think you can do it.

if(eval("!is_array($array".$dimension.")"))
    return false

However, this is another way to do it

function check_md_array($array,$array_levels){
    if(!is_array($array))
         return false;

    foreach($array_levels as $level){
        if(!isset($array[$level]) || !is_array($array[$level]))
            return false;
        $array = $array[$level];
    }

    return true;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜