2012-05-14 2 views
0

create_function을 사용해야합니다. 응용 프로그램을 실행중인 서버에 오래된 버전의 PHP가 있기 때문입니다.중첩 배열을 사용하는 PHP create_function

문제는 항목이 내가 usort가 배열 인으로 통과 것을 내가 배열 내의 값을 기준으로 정렬해야합니다 syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

['distance']과에 대한 참조를 제거 :

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

오류를 제공합니다 ['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

관련 문제