I have a array which comes through an POST request from javascript/jquery. In php the array content is as follows:
[{"name":"Ta","def":"somestring"},{"name":"WSCall","def":"somestring"},{"name":"manual","def":"somestring"}]
How do I iterate over this array to get the keys and values?
When I do: json_decode($_POST['shape_defs'])
How do I iterate over this array. Doing foreach says:
Invalid argument supplied for foreach()
While the (current) other two answers do get working code, they fail to address why you get the error you do.
$data = json_decode($j);
var_dump($data);
This will produce an object, with keys as properties. An object is not valid to be passed to foreach unless it implements Traversable.
What you need to do is:
$data = json_decode($j,true);
This will make objects be associative arrays instead, which are compatible with foreach and most likely the rest of your code.
When there's a definite number of children, you can use nested foreach-loops:
$json = '[{"name":"Ta","def":"somestring"},{"name":"WSCall","def":"somestring"}, {"name":"manual","def":"somestring"}]';
$decode = json_decode($json, true);
foreach ($decode as $k1 => $v1) {
foreach ($v1 as $k2 => $v2) {
echo "$k2: $v2, ";
}
echo "<br>";
}
It will output this:
name: Ta, def: somestring, <br>
name: WSCall, def: somestring, <br>
name: manual, def: somestring, <br>
$j= '[{"name":"Ta","def":"somestring"},{"name":"WSCall","def":"somestring"},{"name":"manual","def":"somestring"}]';
$data = json_decode($j,true);
foreach($data as $key=>$val){
foreach($val as $k=>$v){
echo "Key :".$k." Value :".$v."<br />";
}
}
Related
So Here is my php file code
GetUserArray.php
$Users = array('7'=>'samei', '4'=>"chaya", '10'=>'abetterchutia');
echo json_encode($Users);
and this is my ajax request
$.ajax({
url: './GetUserArray.php',
type: 'POST',
dataType: "json",
success: function(users) {
console.log(users);
$.each( users, function( key, value ) {
console.log(key, value);
});
}
});
now what it gives me is in the console is an object sorted by the keys of that array while i want the orignal order which was 7 4 10 in my php file
Object {4: "chaya", 7: "samei", 10: "abetterchutia"}
4 chutiya
7 sali
10 abetterchutia
The problem with using hashmaps is that they don't actually specify order. Though, in PHP, an array is actually an ordered hashmap, so it does. Once you translate that into an object in Javascript, the order is no longer preserved. The only way to guarantee order in Javascript is to use an array.
So in PHP this works as expected and preserves order.
$arr = [4 => "I'm first", 1 => "I'm second", 3 => "I'm third"];
foreach($arr as $value) {
echo $value, "\n";
}
Which gives us
I'm first
I'm second
I'm third
But encode that to Javascript Object Notation (i.e. JSON) and you get an object, because in Javascript arrays don't have keys, they have indexes.
echo json_encode($arr);
Gives us...
{"4":"I'm first","1":"I'm second","3":"I'm third"}
If you tried to do the same in Javascript with this object you might not get the same order
var obj = {"4":"I'm first","1":"I'm second","3":"I'm third"};
var s = "";
for(var x in obj) {
s += + obj[x] + "\n";
}
document.write("<pre>" + s + "</pre>");
This might give you something more like...
I'm second
I'm third
I'm first
So the only way to fix that is to use an array...
json_encode(array_values($arr));
Now this gives us...
["I'm first","I'm second","I'm third"]
And the order is maintained.
However, if you want to preserve the keys as well, you'll have to create an array of objects.
$json = [];
foreach($arr as $key => $value) {
$json[] = [$key => $value];
}
echo json_encode($json);
Now you get...
[{"4":"I'm first"},{"1":"I'm second"},{"3":"I'm third"}]
Which in javascript, works perfectly as expected...
for(var x in obj) {
for(var n in obj[x]) {
obj[x][n]; // now you can both maintain order and have access to the key
}
}
...
$php_array = mysqli_fetch_all($result,MYSQLI_ASSOC);
?>
<script type='text/javascript'>
<?php
$js_array = json_encode($php_array);
echo "var location = ". $js_array . ";\n";
?>
</script>
How can I modify the above code that gives me this output (an array of objects methinks?)
var javascript_array = [
{"city":"Hermosa Beach","lat":"33.860069","lng":"-118.398784"},
{"city":"San Jose","lat":"34.694628","lng":"-118.398784"},
.... ]
to give me this... (an array of arrays?)
var javascript_array = [
["Hermosa Beach",33.860069,-118.398784],
["San Jose",34.694628",-118.398784],
.... ]
without a bunch of foreaching's...
Use MYSQLI_NUM instead of MYSQL_ASSOC when you call mysqli_fetch_all(). Then the rows will be indexed arrays instead of associative arrays.
Although I don't know why you would want the array to be like this. Arrays should be used for uniform data, objects should be used for heterogeneous data.
thanks, this works and is very lean...
<?php
$query = "SELECT * FROM file";
$result = $con->query($query);
// Fetch all rows and return the result-set as an associative array:
// using numeric keys for the array, instead of creating an associative array.
$php_array = mysqli_fetch_all($result,MYSQLI_NUM);
?>
<script type='text/javascript'>
<?php
// create a JSON representation of a value that javascript will understand
$js_array = json_encode($php_array);
// dump json object into javascript variable 'locations'
echo "var locations =" . $js_array . ";\n";
?>
</script>
I use jquery and ajax to retrieve a dynamically made array made in php, like so:
$json = array();
while ($row = $stmt->fetch_assoc()) {
$json['item_'.$row['id']] = $row['name'];
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($json);
exit;
If I test the php file in browser, it outputs:
{"item_3":"Simon","item_1":"Miriam","item_2":"Shareen"}
So far so good. But how do I use that array in jquery?
I have this jquery ajax:
$.getJSON( "json.php", function(data) {
console.log(data);
});
And testing that page in browser, it put this in console:
Object {item_3: "Simon", item_1: "Miriam", item_2: "Shareen"}
And that's ok right? Or should item_x also be in quotes?
Now, how do I USE that array in jquery?
If I try console.log(data[0]) it puts undefined
As i mentioned in comments, php associative arrays become javascript objects, which cant be accessed numericaly.
A solution would be to send an array of objects instead:
while ($row = $stmt->fetch_assoc()) {
$json[]= ['key'=>'item_'.$row['id'] , 'value' => $row['name']];
}
the in js:
data[0].key;
data[0].value;
EDIT obviously key is a misleading name in this example, better to call it something else:
$json[]= ['id'=>'item_'.$row['id'] , 'value' => $row['name']];
//js
data[0].id;
Try to use $.each() to iterate through that object,
$.each(data,function(key,val){
console.log(key,val);
});
DEMO
If you want to access it without iterating it then simply use bracket notation
data['item_3'] //Simon
Or directly access it like,
data.item_3 //Simon
Then convert it like an array as per your wish like this,
var obj = {"item_3":"Simon","item_1":"Miriam","item_2":"Shareen"};
var convertedArray = $.map(obj,function(val,key){
var obj = {}; obj[val] = key;
return obj;
});
DEMO
I am having a difficulty retrieving a series of json data from php to my JavaScript, file..
Firstly, I have a series of json data stored in an array in php, and echoing each by wrapping it in the for loop to my JavaScript file,
<?php
$result = array('{"one": "test","two": "test"}','{"three": "test","four": "test"}');
for ($i = 0; $i < count($result); ++$i) {
echo $result[$i];
}
?>
in my JavaScript,
$.ajax({
url: "visualiser/visualiser_RouteList.php",
dataType: "JSON",
async: false,
success: function(data){
console.log(data);
}
});
My console does not display anything at all, not recognizing each array element as a json..
but if I send just one array element specifically, for example,
echo $result[0];
then it successfully displays,
Object {one: "test", two: "test"}
why can't I pass a series of json data in an array from php in my ajax call?
It doesn't work because you are generated malformed JSON. The output of your script is
{"one": "test","two": "test"}{"three": "test","four": "test"}
When you access the first element of the array only you get
{"one": "test","two": "test"}
Which is valid.
PHP has json_encode which will do this work for you, so your code would become
$result = array(
array('one' => 'test', 'two' => 'test'),
array('three' => 'test', 'four' =>'test')
);
echo json_encode($result);
giving the output
[{"one":"test","two":"test"},{"three":"test","four":"test"}]
Your code will output this:
{"one": "test","two": "test"}{"three": "test","four": "test"}
This is invalid JSON, so obviously will not work. (Try parsing it with JSON.parse and you'll see.)
You actually need to send the data as an array, so replace your for loop with a simple json_encode call:
echo json_encode($result);
This will output
[{"one": "test","two": "test"},{"three": "test","four": "test"}]
This is valid JSON, and can be parsed into a Javascript array.
Also can you this script
function doj($json){
$result = json_encode($json);
return json_decode($result, true);
}
$json = array(
'{"one": "test","two": "test"}',
'{"three": "test","four": "test"}'
);
$j = doj($json);
foreach($j as $k=>$v){
$extractagain = json_decode($v);
print_r($extractagain);
}
and the output is:
stdClass Object ( [one] => test [two] => test ) stdClass Object ( [three] => test [four] => test )
var labels = new Array();
<?php foreach($crud_data as $cd ) { ?>
labels['<?php echo $cd['name'] ; ?>'] = '<?php echo $cd['label'] ; ?>';
<?php } ?>
$.post('url.php' , { labels:labels} );
Why can I not send labels array like this? It doesn't show anything in Firebug.
My console.log(labels) result:
[]
avatar
"avatar"
email
"email"
id
"id"
name
"name"
password
"password"
if i populate array like this
<?php foreach($crud_data as $cd ) { ?>
labels.push('<?php echo $cd['label'] ; ?>');
<?php } ?>
$.post('url.php' , { labels:labels} );
it works fine !
Oh I see now. If you have string keys, you have to use an object, not an array:
var labels = {};
Arrays in JavaScript are supposed to only hold elements with numeric keys. While you can assign arbitrary properties to arrays, they are not considered to be elements of the array and thus ignored by most processes which deal with arrays.
Additionally you might want to have a look at jQuery.param to see how jQuery will convert the input to a transport-able string and adjust your data structure accordingly.
labels['<?php echo $cd['name'] ; ?>'] =
It seems you want to create an associative array, which is in fact an object in JavaScript (JavaScript has no dedicated associative arrays). So the array itself is in fact empty because you are adding properties to the array object.