Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON to PHP Associative array

would any of you know a good way to put this into an associative array . I have tried json_decode but found it to not be much help.

This is the data i need to put into an associative array:

{
  "data": [
    {
      "name": "Joe Bloggs",
      "id": "203403465"
    },
    {
      "name": "Fred Bloggs",
      "id": "254706567"
    },
    {
      "name": "Barny Rubble",
      "id": "453363843"
    },
    {
      "name": "Homer Simpson",
      "id": "263508546"
    }
  ]
}

EDIT:

After I accepted the answer, I remembered why I thought that the json_decode wasn't working.

Instead of having an associative array like this:

[0] => Array
(
    [name] => Joe Bloggs
    [id] => 203403465
)

I wanted one like this:

Array
(
    [Joe Bloggs] => 45203340465
    [Fred Bloggs] => 65034033446
)

Unfortunately, I had forgotten this at the time.. but I have resolved my issue now anyway.

Thanks for all of your help!

like image 763
vimist Avatar asked Dec 09 '22 15:12

vimist


2 Answers

json_decode works for me on your data:

print_r(json_decode('{
       "data": [
          {
             "name": "Joe Bloggs",
             "id": "203403465"
          },
          {
             "name": "Fred Bloggs",
             "id": "254706567"
          },
          {
             "name": "Barny Rubble",
             "id": "453363843"
          },
          {
             "name": "Homer Simpson",
             "id": "263508546"
          }
       ]
    }
', true));

Output:

Array
(
    [data] => Array
        (
            [0] => Array
                (
                    [name] => Joe Bloggs
                    [id] => 203403465
                )

            [1] => Array
                (
                    [name] => Fred Bloggs
                    [id] => 254706567
                )

            [2] => Array
                (
                    [name] => Barny Rubble
                    [id] => 453363843
                )

            [3] => Array
                (
                    [name] => Homer Simpson
                    [id] => 263508546
                )

        )

)

Setting the second argument to true returns an associative array.

like image 159
webbiedave Avatar answered Dec 25 '22 23:12

webbiedave


You have to make a new array

$json_array = json_decode($_POST['json'], true);
$assoc_array = array();

for($i = 0; $i < sizeof($json_array); $i++)
{
     $key = $json_array[$i]['name'];
     $assoc_array[$key] = $json_array[$i]['value'];
}

you will get your associative array in $assoc_array and you can now directly access using indexes.

like image 27
AndroidLearner Avatar answered Dec 25 '22 22:12

AndroidLearner