简体   繁体   中英

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.

Here is my php. I call it 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. 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] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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