0

i have some problem, how to store value of php array variable to javascript array variable because i want to manipulate data in javascript here's my code

<?php  
$coor= array('-7.175993,112.650729|-7.17616,112.651139|-7.176591,112.650968|-7.176413,112.650552|-7.176104,112.650437','-7.176331,112.649924|-7.17632,112.650053|-7.176629,112.650048|-7.176629,112.649914');
?>

And i want to store all the values from $coor to var allcoor = new Array(), what i've been trying is use json_encode

<script>
var allcoor=new Array();
allcoor = "<?php foreach ($cobadeh as $t){echo json_encode($t);} ?>";
//for some example of manipulation array variable javascript
mySplitResult = allcoor[0].split("|");
...
</script>

What I want is manipulation of javascript array variable, and that code didn't work, can anyone help?

2 Answers 2

1

You need to start out with a php array that mirrors the javascript array that you want. Then output the results of json_encode on that array.

For this I am assuming you want an array of arrays.

<?php
$coorStr = "-7.175993,112.650729|-7.17616,112.651139|-7.176591,112.650968|-7.176413,112.650552|-7.176104,112.650437','-7.176331,112.649924|-7.17632,112.650053|-7.176629,112.650048|-7.176629,112.649914";
$coor= explode("|",$coorStr);
$coor = array_map(function($a) { return explode(",", $a); }, $coor);
?>
allcoor = <?php echo json_encode($cobadeh); ?>;

The first explode command splits the string into an array of elements containing each of the coordinate pairs.

The array_map call splits each of element in an array.

Finally the json_encode formats the data correctly for a javascript assignment.

Since the variable is a php array and you want it as a javascript array

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

3 Comments

it doesnt work. i have two element in variable '$cobadeh', and after i successing store data from '$cobadeh' to 'allcoor', i want to manipulation first element in 'allcoor', and i try 'mySplitResult = allcoor[0].split("|");' but didnt work, any suggestions?
@BryanAndiGerrardo Filled out the answer some more in hopes that it would produce the output you want. If you need something different show a bit of how you want the json string to look.
sorry, my fault, i've been trying again, your suggestion was right, thank you masbroo
1

first you create an array in the php side

$coor='-7.175993,112.650729|-7.17616,112.651139|-7.176591,112.650968|-7.176413,112.650552|-7.176104,112.650437','-7.176331,112.649924|-7.17632,112.650053|-7.176629,112.650048|-7.176629,112.649914';

$corar = explode("|", $coor);

and then in the javascript side you can do

var allcoor = <?php echo json_encode($corar); ?>;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.