1

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 =]

2
  • window.test[0][1] to get the value: E1 Commented Jul 26, 2015 at 7:03
  • If you want named properties, use an associative array. Commented Jul 26, 2015 at 7:03

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.