Shubham
Shubham

Reputation: 43

Get values from JSON array in PHP with the following format?

I have got this array from the Android developer whom I am working with and I have to get the values of the key name from the following array:

[ 
   { 
      "data":"[{\"name\":\"step 1 kdfhghdkgjdf\\nkjdhfgkjhdkjghd\\nkdfjhgkjdhfg\\n\\n\\ndfjhgkjdfjhgdfgd\\n\"},{\"name\":\"step 2 dhfgkjdfhkhkjchjkfd\\ndkjhjdf\\njhkdfhkghdkfhgkdhg\\n\\n\\ndfjhgkjdfhgdfhgkjdhfgkjhdf\"},{\"name\":\"step 3 kkkkkkkkkk\"},{\"name\":\"step 4 ljlejrhlflhgf\\n\\n\\ndfhjk\"}]",
      "status":1
   }
]

I have tried doing the following:

 <?php
    $s = '[
  {
    "data": "[{\"name\":\"step 1 kdfhghdkgjdf\\nkjdhfgkjhdkjghd\\nkdfjhgkjdhfg\\n\\n\\ndfjhgkjdfjhgdfgd\\n\"},{\"name\":\"step 2 dhfgkjdfhkhkjchjkfd\\ndkjhjdf\\njhkdfhkghdkfhgkdhg\\n\\n\\ndfjhgkjdfhgdfhgkjdhfgkjhdf\"},{\"name\":\"step 3 kkkkkkkkkk\"},{\"name\":\"step 4 ljlejrhlflhgf\\n\\n\\ndfhjk\"}]",
    "status": 1
  }
]';
    $obj = json_decode($s,true);
    echo $obj[0]['data']
    ?> 

Which gives me following output:

[
  {
    "name": "step 1 kdfhghdkgjdf kjdhfgkjhdkjghd kdfjhgkjdhfg dfjhgkjdfjhgdfgd "
  },
  {
    "name": "step 2 dhfgkjdfhkhkjchjkfd dkjhjdf jhkdfhkghdkfhgkdhg dfjhgkjdfhgdfhgkjdhfgkjhdf"
  },
  {
    "name": "step 3 kkkkkkkkkk"
  },
  {
    "name": "step 4 ljlejrhlflhgf dfhjk"
  }
]

But I want just the values of the key name like:

step 1 kdfhghdkgjdf kjdhfgkjhdkjghd kdfjhgkjdhfg dfjhgkjdfjhgdfgd
step 2 dhfgkjdfhkhkjchjkfd dkjhjdf jhkdfhkghdkfhgkdhg dfjhgkjdfhgdfhgkjdhfgkjhdf
step 3 kkkkkkkkkk
.
.
.

My question is similar to this one: Get value from JSON array in PHP except the format is different.

Can I get the values in this format? If so, how? If not, is the format incorrect?

Upvotes: 3

Views: 2861

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

Assuming $obj[0]['data'] actually has the JSON that you posted, just decode and extract the name columns:

foreach(array_column(json_decode($obj[0]['data'], true), 'name') as $name) {
    echo $name;
}

Upvotes: 3

AterLux
AterLux

Reputation: 4654

First of all you have not a json-structure inside the "data" field, but just a string, which contains json data.

Therefore you did it wrong, when convert the data into a constant value. You have to double all backslashes first.

Then you can get the "data" element and perform json_decode once more.

<?php
    $s = '[
  {
    "data": "[{\\"name\\":\\"step 1 kdfhghdkgjdf\\\\nkjdhfgkjhdkjghd\\\\nkdfjhgkjdhfg\\\\n\\\\n\\\\ndfjhgkjdfjhgdfgd\\\\n\\"},{\\"name\\":\\"step 2 dhfgkjdfhkhkjchjkfd\\\\ndkjhjdf\\\\njhkdfhkghdkfhgkdhg\\\\n\\\\n\\\\ndfjhgkjdfhgdfhgkjdhfgkjhdf\\"},{\\"name\\":\\"step 3 kkkkkkkkkk\\"},{\\"name\\":\\"step 4 ljlejrhlflhgf\\\\n\\\\n\\\\ndfhjk\\"}]",
    "status": 1
  }
]';
    $obj = json_decode($s,true);
    $data = json_decode($obj[0]['data'], true);

    foreach($data as $item) {
      print($item['name'] . "\r\n");
    }

Upvotes: 2

Related Questions