How Do I Access JS Array By ID

Hi Experts,

I have the below code, which works, but instead of data[1].fName to give me "Aaron", how can I provide 813(the id) and still get Aaron?

The situation is that I have a list of ids, and I would like to add them to a dropdown, but in the order of my id listing.

<?php

$data = Array("0" => Array(
                    "id" => "1625"
                    ,"0" => "1625"
                    ,"fName" => "A.J.:Woodbine Hotel and Suites"
                    ,"1" => "A.J.:Woodbine Hotel and Suites"
                    ,"lName" => NULL
                    ,"2" => NULL
                    ,"phone" => NULL
                    ,"3" => NULL
                    ,"archived" => "0"
                    ,"4" => "0"
                    ,"comments" => NULL
                    ,"5" => NULL
                )
        
            ,"1" => Array(
                    "id" => "813"
                    ,"0" => "813"
                    ,"fName" => "Aaron"
                    ,"1" => "Aaron"
                    ,"lName" => NULL
                    ,"2" => NULL
                    ,"phone" => NULL
                    ,"3" => NULL
                    ,"archived" => "0"
                    ,"4" => "0"
                    ,"comments" => NULL
                    ,"5" => NULL
                )
);

$js_array = json_encode($data);

?>
  <script type="text/javascript">
var data = <?php echo $js_array; ?>;
alert( data[0].id );
</script>
 

Open in new window


Thank you
APD TorontoSoftware DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dave BaldwinFixer of ProblemsCommented:
how can I provide 813(the id) and still get Aaron?
You can't do that directly because javascript array indexes are ONLY numeric starting at 0.  You have to build the array and search thru it to find the pseudo-index you want.

And if you look at the 'View Source' generated by your code you will see that you have a JSON object and Not a javascript array.  They are not the same.
APD TorontoSoftware DeveloperAuthor Commented:
APD TorontoSoftware DeveloperAuthor Commented:
So basically, I need to loop through my array?
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Dave BaldwinFixer of ProblemsCommented:
You don't have a javascript array at all.  That is a JSON object.  You've been posting about this for a while.  Your first problem is the redundant data and the second is the organization that does not meet your needs.

This is a simplified version that uses the JSON object, Not an array.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>PHP2JS Array</title>
</head>
<body>
<h1>PHP2JS Array</h1>
<?php

$data = Array("0" => Array(
                    "id" => "1625"
                    ,"fName" => "A.J.:Woodbine Hotel and Suites"
                    ,"lName" => NULL
                    ,"phone" => NULL
                    ,"archived" => "0"
                    ,"comments" => NULL
                )
        
            ,"1" => Array(
                    "id" => "813"
                    ,"fName" => "Aaron"
                    ,"lName" => NULL
                    ,"phone" => NULL
                    ,"archived" => "0"
                    ,"comments" => NULL
                )
);

$js_data = json_encode($data);

?>
  <script type="text/javascript">
var data = <?php echo $js_data; ?>;
alert( data[0].id );
document.write(data[0].id+' '+data[0].fName+'<br>');
document.write(data[1].id+' '+data[1].fName+'<br>');
</script>

</body>
</html>

Open in new window

APD TorontoSoftware DeveloperAuthor Commented:
Dave,

As I mentioned in my other post, the duplicate data is from PDO's fetchAll() method, so nothing I can do about that.  I tried fetch_assoc() as it was suggested, that method does not exist.

Secondly, your code does not address my question: how can I access directly by the id?

Thank you
Dave BaldwinFixer of ProblemsCommented:
how can I access directly by the id
I don't think you can.  Javascript and JSON do not support anything but numerical indexes.  You have to do a search by looping thru the data until you find the one you want.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
hieloCommented:
>>How Do I Access JS Array By ID
This is a PHP issue, not a javascript issue.  You just need to "re-arrange" your $data so that the first/top level indices correspond to the values in the `id` column.

Instead of just fetchAll(PDO::FETCH_ASSOC) try fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC)
Dave BaldwinFixer of ProblemsCommented:
I think that "fetch(PDO::FETCH_ASSOC);" will return what you want without the duplication.  http://php.net/manual/en/pdostatement.fetch.php
Ray PaseurCommented:
tried fetch_assoc() as it was suggested, that method does not exist.
There are better ways to get results sets from PDO.  Search this page for $pdos->fetchAll(PDO::FETCH_OBJ). The advantage of using objects instead of arrays is mostly one of convenient syntax - you do not need a lot of fiddly punctuation to use the object notation or to embed the returned variables in other strings.  When you get more advanced with PHP object-oriented programming, you may find other valuable aspects of fetching your data in the form of objects, and you won't have to change the underlying interface to the query results set!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.