Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is $value in this PHP foreach loop an array?

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)

like image 512
Wesley Smith Avatar asked Apr 15 '26 22:04

Wesley Smith


1 Answers

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']
};
like image 132
Jan.J Avatar answered Apr 17 '26 13:04

Jan.J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!