In my jQuery code I'm creating an object like this:
var fields = [
['title','New Title'],
['description', 'New Description'],
['stuff', ['one','two','three']]
];
var objectsArray=[
{
fields:fields
}
];
var saveObject = {
command: 'test',
callback:'testResopnse',
objects: objectsArray
}
Which I then send via ajax to a PHP page like this:
saveDataAsParseObjects(saveObject)
function saveDataAsParseObjects(saveObj){
$.ajax({
type: "POST",
dataType: "json",
url: "php/parseFunctions.php",
data: {data:saveObj},
success: function(response) {
console.log(response);
},
error: function(response) {
console.log(response);
}
});
};
In my PHP page I'm doing this:
$data= $_POST['data'];
if($data['command'] == 'test'){
testStuff($data);
}
function testStuff($data){
$objects = $data['objects'];
foreach($objects as $object){
$fields = $object['fields'];
foreach($fields as $column => $value){
echo is_array($value) ? 'Array, ' : 'not an Array, ';
}
}
}
Considering my original fields
array on the jQuery page, I expect testStuff()
to return:
'not an Array, not an Array, Array,'
.
But instead it returns:
'Array, Array, Array,'
Why is $value
an array in this foreach loop when I expect it to by a string?
foreach($fields as $column => $value)
You need to loop it one more time, since your fields
array is an array of arrays (take this pseudo as an example):
Array(
INDEX => Array(...),
INDEX => Array(...),
INDEX => Array(...),
)
All you need is 1 more loop:
$fields = $object['fields'];
foreach($fields as $column => $value){
foreach($value as $key => $obj) {
echo is_array($obj) ? 'Array, ' : 'not an Array, ';
}
}
You are iterating over this collection in most nested foreach:
var fields = [
['title','New Title'],
['description', 'New Description'],
['stuff', ['one','two','three']]
];
So every $value
is also an array e.g. ['title','New Title']
. You should iterate over it one more time or change fields to object like this:
var fields = {
title: 'New Title',
description: 'New Description',
stuff: ['one','two','three']
};
because the javascript variable "fields" is an array of array.
When you loop throught $fields, you loop throught this variable (aka objectsArray[0].fields)
Because each $value is element of fields array. And each element of that array is another array.
So
['title','New Title'],
in
var fields = [
['title','New Title'],
['description', 'New Description'],
['stuff', ['one','two','three']]
];
is array of title and New title.
If you debug or var_dump($value) in php you will see that the output is
array (size=2)
0 => string 'title' (length=5)
1 => string 'New Title' (length=9)
array (size=2)
0 => string 'description' (length=11)
1 => string 'New Description' (length=15)
array (size=2)
0 => string 'stuff' (length=5)
1 =>
array (size=3)
0 => string 'one' (length=3)
1 => string 'two' (length=3)
2 => string 'three' (length=5)