我希望有人可以帮助我试图找到一种方法来找到像PHP in_array
这样存在的数组中的值。
我有两个变量PTOWN
和ADDRESS
。我想找出PTOWN
是否在数组中的任何位置?
答案 0 :(得分:0)
您在寻找if $data(ADDRESS("street 1")) write "found"
吗?
答案 1 :(得分:0)
您是否在键或节点值中寻找PTOWN
?如果可以在键中找到PTOWN
,则可以使用$ ORDER查找与您拥有的内容最匹配的内容。假设你有一个这样的数组:
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将返回与您的搜索字词最匹配的密钥,并且也会在MUMPS的订购系统中返回。因此$ORDER(Array("Pa"))
返回“Paris”,$ORDER(Array("Mad"))
返回“Madrid”,$ORDER(Array("Alameda"))
返回“Boston”,因为“Boston”是数组中“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
,则必须使用循环方法。
答案 2 :(得分:0)
假设PTOWN为“ $ needle”,地址为“ $ 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!