0

我希望有人可以帮助我试图找到一种方法来查找数组中的值,例如 PHP in_array

我有两个变量PTOWNADDRESS. 我想查找是否PTOWN在数组中的任何位置?

4

3 回答 3

0

假设 PTOWN 是 '$needle' 而 ADDRESS 是 '$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!
于 2019-03-06T19:43:17.440 回答
0

您是在寻找PTOWN节点的键还是值?如果PTOWN可能在keys中找到,您可以使用 $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将在数组的值中找到,则必须使用循环方法。

于 2018-02-14T03:17:32.793 回答
0

你在找if $data(ADDRESS("street 1")) write "found"吗?

于 2018-02-07T12:13:25.130 回答