PHP create_function with nested arrays

强颜欢笑 提交于 2019-12-25 08:26:01

问题


I need to use create_function because the server the application is running on has an outdated version of PHP.

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

Gives an error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

Removing the references to ['distance'] and ['order-dir'] removes this error.

Does anyone know how to use create_function with nested arrays?


回答1:


Don't use create_function in this instance. You can also write it like this:

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



回答2:


You need to escape your variable names. Per the create_function documentation (emphasis mine):

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.

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.



来源:https://stackoverflow.com/questions/10590877/php-create-function-with-nested-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!