PHP to JavaScript Array

Hi Experts,

In PHP I have the following array:
Array
(
    [0] => Array
        (
            [id] => 1625
            [0] => 1625
            [fName] => A.J.:Woodbine Hotel and Suites
            [1] => A.J.:Woodbine Hotel and Suites
            [lName] => 
            [2] => 
            [phone] => 
            [3] => 
            [archived] => 0
            [4] => 0
            [comments] => 
            [5] => 
        )

    [1] => Array
        (
            [id] => 813
            [0] => 813
            [fName] => Aaron
            [1] => Aaron
            [lName] => 
            [2] => 
            [phone] => 
            [3] => 
            [archived] => 0
            [4] => 0
            [comments] => 
            [5] => 
        )
...
...
}

Open in new window


My question is, how can I copy this into- a JavaScript Array?

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.

hieloCommented:
use json_encode():

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

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

Open in new window

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
Slick812Commented:
greetings  APD_Toronto,  If you do much in PHP to Javacript variables, then you may can use some code like this, which has a $newArray in PHP and places it in a Javascript variable newArray. .
<!DOCTYPE HTML>
<html lang="en"><head>
<title>PHP array to Javascript Code write</title></head><body bgcolor="#e3f7ff"><h3>PHP array to Javascript Code write</h3>
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);

$newArray = array(
  array('id' => 1625,
  0 => 1625,
  'fName' => 'A.J.:Woodbine Hotel and Suites',
  1 => 'A.J.:Woodbine Hotel and Suites',
  'lName' => 'last',
  2 => '',
  'phone' => '555-2345',
  3 => '555-2345',
  'archived' => 0,
  4 => 0,
  'comments' => 'comment "1"',
  5 => 'comment "1"'
  ),
  
  array('id' => 813,
  0 => 813,
  'fName' => 'Aaron',
  1 => 'Aaron',
  'lName' => 'Smith',
  2 => 'Smith',
  'phone' => '111-1111',
  3 => '111-1111',
  'archived' => 0,
  4 => 0,
  'comments' => 'comment "2"',
  5 => 'comment "2"'
  )
);
?>
<hr>
the new Array has


<script>/* <![CDATA[ */
var newArray = <?php
$jsOut = '[';
for($i=0; $i < count($newArray); ++$i) {
  $jsOut .= '[';
  for ($ar = 0; $ar < 6; ++$ar) {
    if(is_string($newArray[$i][$ar])) {
    $jsOut .= '"'.str_replace('"', '\\"', $newArray[$i][$ar]).'",';
	} else {
    $jsOut .= $newArray[$i][$ar].',';
	}
    }
  $jsOut = substr($jsOut, 0, -1);
  $jsOut .= '],';
  }
$jsOut = substr($jsOut, 0, -1);
$jsOut .= '];';
echo $jsOut;
?>

document.write(newArray.length+" elements<br />");
document.write("the 0 0 element in sub array is = "+newArray[0][0]+", , the 1 1 element is= "+newArray[1][1]+", , the 0 5 is= "+newArray[0][5]);
/* ]]> */</script>
</body></html>

Open in new window


This PHP code is set up for your specific PHP array, and outputs in Javascript a Two Level array, But In Javascript you can NOT HAVE string keys for arrays, so my JS eliminates the string keys, and just uses the number keys, but you have duplicate data, which is just a waste of array space.
hieloCommented:
>>my JS eliminates the string keys, and just uses the number keys
A better suggestion would be to eliminate the redundant data on the server before using json_encode().

Instead of using :
 
$row = $result->fetch_array(); 

Open in new window

which will give you duplicate data with numeric and string keys (corresponding to the column names of your executed query)

use:
$row = $result->fetch_row();

Open in new window

if you only want numeric keys.

OR
$row = $result->fetch_assoc();

Open in new window

if you only want string keys.  You can still use the json_encode() function I suggested in my first post.
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

APD TorontoSoftware DeveloperAuthor Commented:
What do you mean by I have duplicate data?

If you referring for example
  [id] => 1625
            [0] => 1625
            [fName] => A.J.:Woodbine Hotel and Suites
            [1] => A.J.:Woodbine Hotel and Suites

Open in new window


As in [id] and [0] both equaling 1625 I thought that this was PHP's representation of element zero which can also be accessed by id?
hieloCommented:
>> As in [id] and [0] both equaling 1625
Yes, that's what I meant by "duplicate".  However, this is not "PHP's representation".  In other words, if you declare:
$data = Array("fName"=>"A.J.:Woodbine Hotel and Suites");

Open in new window


you will not "auto-magically" have another element with index 0 in it set to the same value as "fName".  The duplicate values in your array structure is the doing of your DB driver.  Very rarely do you need "enumerated" AND "string" keys after querying a DB.  If you don't need both, my suggestion is to use either enumerated keys ( use fetch_row() ) OR string keys ( use fetch_assoc() ).
APD TorontoSoftware DeveloperAuthor Commented:
Thhanks
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.