php
  • jquery
  • 2016-01-15 28 views 0 likes 
    0

    我正在給jQuery對象鍵和PHP關聯數組值:充分利用jQuery對象特定鍵和值

    $names = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); 
    $js = json_encode($names); 
    echo 'var names= ' . $js . ";"; 
    

    現在我知道如何通過所有的名字的迭代,並得到他們的鍵和值:

    $.each(names, function(key, value){ 
        alert(key + value); 
    }); 
    

    但我只需要具體的價值。例如,如何在不遍歷所有名稱的情況下只獲取「Ben」和「37」?

    +1

    '的console.log(names.Ben);'? –

    +0

    但我不知道關鍵。我不知道這個名字是本。我想獲取密鑰以及值 – matip

    +0

    嘗試添加新的Array(),如: echo'var names = new Array('。$ js。「);」; – Yehia

    回答

    2

    你可以做到這一點使用Object.keys

    var index = 1; // the nth key you want to fetch, 1 will be second 
    key = Object.keys(names)[index]; 
    value = names[key]; 
    
    console.log(key + ' -> ' + value); 
    

    將輸出

    Ben -> 37 
    
    +0

    謝謝,它的工作原理 – matip

    相關問題