我希望有人可以帮助我试图找到一种在像PHP in_array
这样的数组中找到值的方法。
我有两个变量PTOWN
和ADDRESS
。我想找到PTOWN
是否在数组中的任何地方?
您是否正在寻找if $data(ADDRESS("street 1")) write "found"
?
您是在键或节点的值中寻找PTOWN
吗?如果可以在键中找到PTOWN
,则可以使用$订单找到与拥有的最接近的匹配。假设您有这样的数组:
new PTOWN,Address,Array
set PTOWN="Paris"
set Address="Some address"
;
set Array("Paris")="123 Avenue Louis Pasteur"
set Array("Madrid")="434 Calle De Duermos"
set Array("Boston")="1522 Market Street"
;
if $ORDER(Array(PTOWN))=PTOWN d
...
$订单将返回与您的搜索词最匹配的密钥,并且在腮腺炎的订购系统中也是在它之后进行的。因此,$ORDER(Array("Pa"))
返回"巴黎",$ORDER(Array("Mad"))
返回"马德里",$ORDER(Array("Alameda"))
返回"波士顿",因为"波士顿"是阵列中" Alameda"之后的下一件事。
您也可以使用它在数组中的所有键上循环:
new nodeName
set nodeName="" ; you have to pass $ORDER "" to get the first thing in the array
;
for set nodeName=$ORDER(Array(nodeName)) quit:nodeName="" d
; $ORDER returns "" when you pass it the *last* key in the array, so we can quit this loop when we get that back
;
if nodeName=PTOWN write Array(nodeName)
如果在数组的值中找到PTOWN
,则必须使用循环方法。
假设Ptown是'$针',并且地址为'$ Haystack'(根据IN_ARRAY文档(,并且不知道阵列格式,您可以做的最好的就是:
in_array(needle,haystack)
NEW idx,found,subAry
SET found=0 ; If you want to return 0 instead of "" if not found
;
FOR $ORDER(haystack(idx)) QUIT:idx="" DO QUIT:found
. ; If the format of the array is: array(<index>)=<value>
. IF haystack(idx)=needle SET found=1 QUIT
. ;
. ; If the format of the array is: array(<key>)=<value>
. ; Note: this type of search can be made a bit more efficient, but we're brute-forcing here
. IF idx=haystack SET found=1 QUIT
. ;
. ; If you're using nested keys and values...this is NOT recommended since Cache doesn't really support recursion
. MERGE subAry=haystack(idx)
. SET found=$$in_array(needle,subAry)
;
QUIT found
您会这样称呼:
...=$$in_array(PTOWN,.ADDRESS) ; Don't forget to pass by reference!