2012-05-14 42 views
0

我需要使用create_function,因为运行应用程序的服务器具有过时的PHP版本。使用嵌套数组的PHP create_function

的问题是,该项目我进入usort是数组,我需要通过阵列内的值进行排序:

$sort_dist = create_function('$a, $b', " 
    if($a['order-dir'] == 'asc') { 
     return $a['distance'] > $b['distance']; 
    } 
    else { 
     return $a['distance'] < $b['distance']; 
    }" 
); 

usort($items, $sort_dist); 

给出了一个错误:syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

删除引用['distance']['order-dir']删除此错误。

有谁知道如何使用嵌套数组create_function

回答

1

在这种情况下请勿使用create_function。您也可以这样写:

function sort_by_distance($a, $b) { 
    if($a['order-dir'] == 'asc') { 
     return $a['distance'] > $b['distance']; 
    } 
    else { 
     return $a['distance'] < $b['distance']; 
    } 
} 

usort($items, "sort_by_distance"); // pass the function name as a string 
+0

其他是不需要的... –

+0

不是我的代码;) - 如果你有更好的答案,随时发布它。 – Halcyon

+0

这工作,谢谢! – Matt

1

您需要转义您的变量名称。每create_function文档(重点矿山):

Usually these parameters will be passed as single quote delimited strings. The reason for using single quoted strings, is to protect the variable names from parsing, otherwise, if you use double quotes there will be a need to escape the variable names, e.g. \$avar.

我,应该注意未来的读者,Frits van Campen's answer可能是你应该使用的解决方案,但如果你确实需要使用create_function,我的答案应该工作。

+0

没有尝试过,但它可能会起作用,谢谢。 – Matt