PHP create_function与嵌套数组 [英] PHP create_function with nested arrays
问题描述
我需要使用create_function
,因为运行应用程序的服务器上的PHP版本已经过时.
I need to use create_function
because the server the application is running on has an outdated version of PHP.
问题是我传递到usort
的项目是数组,我需要按数组中的值排序:
The issue is that the items I pass into usort
are arrays and I need to sort by a value within the array:
$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']
的引用将消除此错误.
Removing the references to ['distance']
and ['order-dir']
removes this error.
有人知道如何将create_function
与嵌套数组一起使用吗?
Does anyone know how to use create_function
with nested arrays?
推荐答案
您需要转义变量名.根据 create_function
文档(重点是我):
You need to escape your variable names. Per the create_function
documentation (emphasis mine):
通常,这些参数将作为单引号分隔的字符串传递.使用单引号引起来的字符串的原因是为了保护变量名免于解析,否则,如果使用双引号,则需要转义变量名,例如
\$avar
.
我应该为以后的读者指出,范坎彭的答案可能是您应该使用的解决方案,但如果您绝对使用需要使用create_function
,我的答案应该起作用.
I should note for future readers that Frits van Campen's answer is probably the solution you should use, but if you absolutely need to use create_function
, my answer should work.
这篇关于PHP create_function与嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!