来自php数组的inArray jQuery,找到项目索引

This code, which I've found somewhere online, works fine and it's kind of what I'm trying to accomplish:

$(document).ready(function(){
    var arrData = [ "j", "Q", "u", "e","r","y" ];   
    alert(jQuery.inArray("Q", arrData));
});

However, I have an array from a loop with php/mysql that I output and save like this:

$query = mysql_query("SELECT * FROM geo_orter");
            while(($row = mysql_fetch_assoc($query))){
                $i = $row['ort_id'];
                $result[$i] = $row['ortnamn'];
            };
            $allaOrterjson=json_encode($result);

Then I go ahead and do this, which works:

var allaOrter=<?php echo $allaOrterjson ?>;

    document.write(allaOrter[0] + allaOrter[1] + allaOrter[2]);

and gives me

undefinedAborremålaAbbjörnahall

Here's the issue:

I tried

$(document).ready(function(){
    alert(jQuery.inArray("Aborremåla", allaOrter));
});

but it results in "-1" (Not found).

I'm trying to find out the index nr of an item in the array. Any ideas?

Log result: loggen

The problem here is that json_encode($result); creates a JSON object, not an array. Hence jQuery.inArray isn't working.

Build a JavaScript array instead: [ "value", "value", "value", etc... ];

Or do something like this with the object:

var locations = {
    "Abårremöla" : 1,
    "Stuff" : 2,
    "Ludvika" : 1549
};

var query = "Ludvika";
if(query in locations) {
    var id = locations[query];
    alert(id); //displays 1549
}



For that to work you have to build up the object the other way around in PHP - so a PHP array with the location name as the indexer and the id as the value:

$query = mysql_query("SELECT ort_id, ortnamn FROM geo_orter");
while(($row = mysql_fetch_assoc($query))){
    $index = $row['ortnamn'];     //<- note!
    $result[$i] = $row['ort_id']; //<- note!
};
$allaOrterjson=json_encode($result);

Try this

var my_cars= new Array()
my_cars[0]="Mustang";

my_cars["family"]="Station Wagon";

my_cars["big"]="SUV";

for( var i in my_cars ){
    console.log( my_cars[i] );
}

var n = {
    "0": "Mustang",
    "family": " Station Wagon",
    "big": "SUV"
};
for( var i in n ){
    console.log( n[i] );
}