简体   繁体   English

PHP获取键值或Json数组中的值

[英]PHP get the key value or the value in Json array

I am trying to get either the key or the value, depending on my i send to the server through ajax, but my return from php is not responding as I thought it would. 我试图获取密钥或值,具体取决于我通过ajax发送至服务器的情况,但是我从php返回的响应没有达到我的预期。

Here is my php. 这是我的PHP。 I call it myphp.php. 我称之为myphp.php。

<?php

$m_decoded = $_POST['animal'];

$json = '{"Cat" : "Black", 

  "Dog": "Red",

  "Monkey" : "Yellow"

   }';

$obj = json_decode($json, true);
if(array_key_exists($m_decoded, $obj)){
    print $obj[$m_decoded]; 
}else {
    print array_search($obj[$m_decoded], $obj);
}


//$obj = json_decode($json, true);
//if($obj->{$m_decoded} == NULL){
//  print array_search($obj->{$m_decoded});
//}else {
//  print $obj->{$m_decoded}; 
//}
?>

<script>
$(function() {
    //function startAjax() {
      $(".verse").click(function(e){
          e.preventDefault();

            var cliks = $(this).text();
            $( this ).addClass( "inside" );
            //$("#clickme").text("Calling server");
            $.ajax({
                type: "POST",
                url:"myphp.php",
                data:{"animal" : cliks},
                success:callbackFunction, 
                error:errorFunction
            });
        });
});
    function callbackFunction(data,info) {
                var v = $(".inside").text();
                var val = data;
                //alert(v);
                $(".inside").fadeOut(function(){
                    //alert(v);
                    $(".inside").text(($(".inside").text() == v) ? val : v).fadeIn();
                    $(".inside").removeClass( "inside" );

                });

    }
    function errorFunction(data,info) {
                $(".inside").text("error occurred:"+info);
    }
</script>

My problem is with the php, because i can get the value the first time i click, but the second time I click on the line with the replaced value, I was hoping to get the key from the server but that is not the case. 我的问题与php有关,因为我第一次单击即可获取该值,但是第二次单击具有替换值的行时,我希望从服务器获取密钥,但事实并非如此。 I just want to try to change the text of the link with the color the first time clicked, and back to the animal the second time clicked. 我只想尝试在第一次单击时用颜色更改链接的文本,然后在第二次单击时更改回动物。 Any help would be appreciated. 任何帮助,将不胜感激。

Corrected code for toggle between key and value (color and animal): 更正了用于在键和值(颜色和动物)之间切换的代码:

$obj = json_decode($json, true);
if(array_key_exists($m_decoded, $obj)){
    print $obj[$m_decoded]; 
} else {
    print array_search($m_decoded, $obj);
}

in second case you must search $m_decoded in $obj , not $obj[$m_decoded] . 在第二种情况下,您必须在$obj搜索$m_decoded ,而不是$obj[$m_decoded]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM