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


PHP get the key value or the value in Json array

我试图获得键或值,这取决于我通过ajax发送到服务器,但我从php返回没有响应,因为我认为它会。

这是我的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>

我的问题是与php,因为我可以得到值我第一次点击,但第二次我点击与替换值的行,我希望从服务器获得密钥,但事实并非如此。我只是想尝试改变与颜色的链接的文字第一次点击,并回到动物第二次点击。任何帮助都会很感激。

键和值(颜色和动物)之间切换的更正代码:

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

在第二种情况下,必须在$obj中搜索$m_decoded,而不是$obj[$m_decoded]