Reputation: 157
I want to create an array in js that conteins items, each item is a row form the DB, each item have id and name property.
i create this function in php:
function getECatTest(){
$accountid = getAccountid($_SESSION[get("session_name")]);
$aaa = array();
$query = mysql_query("SELECT * FROM `ExpensesCategorys`");
while($result = mysql_fetch_assoc($query)){
//$cars[$result["category_id"]] = $result["category_name"];
$cars = array($result["category_id"],$result["category_name"]);
array_push($aaa,$cars);
$count += 1;
}
$js_array = json_encode($aaa);
echo "window.test = ".$js_array.";\n";
}
and here is the js code:
<script type="text/javascript">
<?php getECatTest(); ?>
</script>
now this is what i get:
window.test = [["1","E1"],["2","E2"],["3","E3"],["4","E4"],["5","E5"],["6","E6"],["7","E7"],["8","E8"]];
i want to get it sorted like "id": "1", "name": "E1" and so on... and i dont know how to accsses the code :D i mean if i want the id 1 only how i can get it?
i tryed this: window.test[1] but its return the id and the name...what if i want only the name? or only the id?
please help, and write how i can accses the code its important..
TY =]
Upvotes: 1
Views: 51
Reputation: 242
window.test
is a two-dimensional array. You may use:
window.test[0][0] for 0'th element's id
window.test[0][1] for 0'th element's value
or alternatively:
function getECatTest(){
$accountid = getAccountid($_SESSION[get("session_name")]);
$aaa = array();
$query = mysql_query("SELECT * FROM `ExpensesCategorys`");
while($result = mysql_fetch_assoc($query)){
//$cars[$result["category_id"]] = $result["category_name"];
$cars = array('id'=>$result["category_id"],'name'=>$result["category_name"]);
array_push($aaa,$cars);
$count += 1;
}
$js_array = json_encode($aaa);
echo "window.test = ".$js_array.";\n";
}
In javascript use:
for(element in window.test){
alert(element.id + " " + element.name);
}
Upvotes: 0
Reputation: 780842
To get named properties, use an associative array:
$cars = array('id' => $result['category_id'],
'name' => $result['category_name']);
$aaa[] = $cars;
Then the Javascript result will look like:
window.test = [ { "id": "1", "name": "E1" }, { "id": "2", "name": "E2" }, ...];
Then to access the first name, you use window.test[0].name
.
Upvotes: 1