0

I'm trying to parse a PHP multidimensional array into a Javascript array.

So far, I've got:

<?php
 foreach ($array as $key => $userArray){

 echo "array[] = array['{$userArray['name']}', {$userArray['count']}, {$userArray['userId']}]; \n";
 }
?>

from and array that looks like:

$array[] = array(
'name' => 'John Doe',
'userId' => '12',
'count' => '31'
);

Thanks,

2

3 Answers 3

1

Why don't you just use json_encode()?

<?php

  echo 'var array = ' . json_encode( $array );

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

1 Comment

I've just realised that I can do that. :)
0

you want json_encode()

<?php 
    $jsonArray = json_encode($array);
    echo $jsonArray; //outputs {"name": 'John Doe',"userId" : 12, "count" : 31}
?>

1 Comment

gotta be quick in this town!
0

Utilize the json_encode along with the array_map function to do what you need:

echo json_encode(array_map(function($user) 
  return array(
     'name' => $user['name'],
     'userId' => $user['userId'],
     'count' => $user['age']
),$userArray));

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.