views:

82

answers:

4
+1  Q: 

Parsing array data

I am trying to parse this array data that way generated from JQuery and JSON.

Array
(
[d] => Array
    (
        [0] => Array
            (
                [order] => 1
            )

        [1] => Array
            (
                [order] => 2
            )

        [2] => Array
            (
                [order] => 3
            )

        [3] => Array
            (
                [order] => 4
            )

        [4] => Array
            (
                [order] => 5
            )

    )

)

I am trying to save the above date into a mysql table, but cannot seem to parse the data properly to be inserted into the database.

Can anyone help?

+1  A: 

I suppose language is PHP? You might wanna take a look json_decode()-function here: http://php.net/manual/en/function.json-decode.php

Nikkeloodeni
A: 

This looks like the ouput of the function print_r() -- and this is not intented to be parsed.

Instead of trying to parse that, you should work directly with the data your PHP code is receiving from the Ajax request -- i.e. with the JSON data, decoded with json_decode().

Pascal MARTIN
WOW, such quick replies...This is what is sent through the AJAX POST: {"d":[{"order":1},{"order":2},{"order":3},{"order":4},{"order":5}]}And using json_decode, the code below is what I have so far: $data = file_get_contents('php://input'); $data = json_decode(utf8_decode($data), true); foreach ( $data[d] as $key => $value ) { // $this->img_model->update_image_order($id , $order); }My main problem is getting my head round the arrays... Hopefully someone can point me in the right direction.
Sam
A: 

All you have to do is something like this,

foreach ( $data['d'] as $key => $value ) { 
   $id = $value['order'];
   $order = 'order';
   $this->img_model->update_image_order($id , $order); 
}

This assumes the number in JSON is the order ID.

ZZ Coder
Thanks ZZCoder, unfortunately I am getting a couple of errors with this. I am getting "Message: Use of undefined constant d - assumed 'd" and "Message: Undefined variable: order" errors.How can I fix this?
Sam
I don't know the semantics of the message so the code is just an example how to handle the array of array. Just edited to get rid of the errors.
ZZ Coder
A: 

You should use json_decode() (as others have already stated) for decoding your JSON into php arrays. But if I got it right your problem is how to work with PHP arrays so i suggest you check out some good basic tutorial. w3c has decent basic array tutorial here: http://www.w3schools.com/php/php_arrays.asp

veturi