0

This is my Json data:-

{"data":[{"text1":"value1","text2":"value2","text3":"values3"},{"text1":"value1","text2":"value2","text3":"values"},{"text1":"value1","text2":"value2","text3":"values"},{"text1":"value1","text2":"value2","text3":"values"}, ....

How can I get this format ? 0 to length of array.

"0 Line,text1=value,text2=value2,text3=values3"
"1 Line,text1=value,text2=value2,text3=values3"
"2 Line,text1=value,text2=value2,text3=values3"
"3 Line,text1=value,text2=value2,text3=values3"
"4 Line,text1=value,text2=value2,text3=values3"
"5 Line,text1=value,text2=value2,text3=values3"
....

Please kindly help me, I am very new to json. I spent too much hours and getting no result. my code -

$obj = json_decode($json);
echo $obj->data[0]->text1;
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Leonar Aung
  • 151
  • 1
  • 2
  • 11
  • Use true as the second parameter in json_decode and you will get the array. I guess it will be easier fly you to go through it with foreach – Vladislav Aug 03 '17 at 17:49
  • your code is correct now what's your issue you are unable to write data into define format or not able to read the json data because your codeing is correct now just want to apply foreach or for loop and parse data. – Priyanka Sankhala Aug 03 '17 at 18:14
  • Possible duplicate of [How do I extract data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php) – user3942918 Aug 03 '17 at 18:27

2 Answers2

1

You can do it like below:-

<?php

$json = '{"data":[{"text1":"value1","text2":"value2","text3":"values3"},{"text1":"value1","text2":"value2","text3":"values"},{"text1":"value1","text2":"value2","text3":"values"},{"text1":"value1","text2":"value2","text3":"values"}]}';

$json_array = json_decode($json,true); // convert to php array
//print_r($json_array);

foreach($json_array['data'] as $key=>$val){ // iterate over array
  $data ="$key line,";
  foreach($val as $k=>$v){ // iterate over child-array or sub-array you can say
     $data .="$k=$v,";
  }
  echo trim($data,",");
  echo PHP_EOL; // you can use `echo "<br>";` for rendering to browser
}

Output:-https://eval.in/841221 OR https://eval.in/841222 OR https://eval.in/841223 OR https://eval.in/841224

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
0

Json is a fix format string you can easily convert it into json.abusively if you are using json in php used row data not as post or set If you used raw data(pass json via body) use following method php://input

$rawData = file_get_contents("php://input"); $data_array = json_decode($rawData);

Now $data_array is a object array

If you post this josn in get or post direct use

$rawdata = $_POST['jsondata']; $data_array = json_decode($rawData);

Hope is helpful for you

Priyanka Sankhala
  • 808
  • 1
  • 9
  • 25