PHP create_function with nested arrays

2019-09-13 04:30发布

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?

2条回答
smile是对你的礼貌
2楼-- · 2019-09-13 05:05

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
查看更多
爷、活的狠高调
3楼-- · 2019-09-13 05:08

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.

查看更多
登录 后发表回答