dongmaoxi0477 2012-05-14 20:54
浏览 23

带有嵌套数组的PHP create_function

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条回答 默认 最新

  • drau67562 2012-05-14 20:56
    关注

    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
    
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算