Convert JSON to CSV with php (not a script) - php

Each of my users has a JSON encoded string saved to a field called 'json'. There will be multiple multidimensional items but nutrients will not always be an element. This is the format:
$arr = array(
0 => array(
'name' => Input::get('name'),
'amount' => 5,
'time' => '2:00 am',
'nutrients' => array(
'Macro' => array(
'water' => 0,
'carbs' => 0,
),
'Micro' => array(
'zinc' => 0,
)
)
);
$user->json = json_encode($arr);
$user->save();
I want to (in another view) convert $user->json into a CSV file. This is the closest I could get with code I found online but I still get an error ('fputcsv() expects parameter 2 to be array, object given'):
$user = Auth::user();
$json_obj = json_decode ($user->json);
$fp = fopen('file.csv', 'w');
foreach ($json_obj as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
If I use $json_obj = json_decode ($user->json, true); I get the error "Array to string conversion"
Any help is appreciated, let me know if more information is needed. Thank you!

Well you got arrays in your array... thats why you get the error when you're doing the json_decode($data, true). You got to decide how you want to format your other data like "nutrients".
I hope you get the point. The problem is that it expects an array of primitive data and not an array with another array in it.

Related

How do I insert an array at a certain position to another array?

I am trying to make a custom comments system for my website, but I need help with inserting the comment information to the decoded JSON array and then saving it back to the comments file.
I've tried splitting the arrays and pushing the array, but to no prevail.
<?php
$data = array(
'username'=> $_GET['username'],
'email' => $_GET['email'],
'time' => time(),
'content' => $_GET['content']);
$file = fopen("post-comments.json", "r");
$fileData = fread($file,filesize("post-comments.json"));
$decodedData = json_decode($fileData, true);
$insertedArray = array_splice( $data, 3, 0, $decodedData );
var_dump($decodedData);
echo("<br>");
var_dump($insertedArray);
?>
I expect the output to be, as an example, (when the json is encoded again)
{"2": [
{
"username":"John Doe", "email":"john.doe#example.com",
"time":12345,
"content":"Hello World!"
}
]
}
with any other past comments in the file aswell.

Parse string to array like CakePHP form data

I am looking for a way to parse strings in an array to an array which has a similar pattern to how CakePHP handles POST data. Or even a function in CakePHP that would do it.
UPDATED:
Current array:
array(
'data[callers]' => (int) 4,
'data[status]' => 'Unknown',
'data[country_id][107]' => (int) 1,
'data[country_id][150]' => (int) 0
)
Desired result:
array(
'callers' => (int) 4,
'status' => 'Unknown',
'country_id' => array(
(int) 107 => (int) 1,
(int) 150 => (int) 0
)
)
The purpose is saving serialized form data which can later be passed to a PHP function without having to POST the data from the browser.
The data comes from a form which was serialized and saved in the database. CakePHP generates input names in the form with brackets like this: data[country_id][107] and inside the controller you can access it like this $this->request->data['country_id']['107']
But when I serialize the form with javascript and save the raw JSON string in the database I need a way to make it into an array like CakePHP does.
Firstly make sure your array is valid first like:
$data = array (
'callers' => 4,
'status' => 'Unknown',
'country_id' => array(
'107' => 0,
'150' => 0
)
);
JSON ENCODE
Now you can json encode it
$json = json_encode($data);
echo $json; // prints: {"callers":4,"status":"Unknown","country_id":{"107":0,"150":0}}
See ^ it is now a string.
http://php.net/manual/en/function.json-encode.php
JSON DECODE
Then when you need it as an array call json_decode()
json_decode($data, true);
Note the second parameter is setting return array to true else you will get an the json returned as an object.
http://php.net/manual/en/function.json-decode.php

Getting a value from associative arrays PHP

I have an array..
$file=array(
'uid' => '52',
'guarantee_id' => '1116',
'file_id' => '8',
'file_category' => 'test',
'meta' =>'{"name":"IMAG0161.jpg","type":"image\/jpeg","tmp_name":"\/tmp\/phpzdiaXV","error":0,"size":1749244}',
'FileStorage' => array()
)
and I am trying to extract the name using
$fileName = $file['meta'['name'];
which gives me a Illegal string offset 'name' error.
The value of $file['meta'] is a string, not an array. That means your approach to access the value does not work.
It looks like that meta value string is a json encoded object. If so you can decode it and then access the property "name" of the resulting object.
Take a look at this example:
<?php
$file = [
'uid' => '52',
'guarantee_id' => '1116',
'file_id' => '8',
'file_category' => 'test',
'meta' =>'{"name":"IMAG0161.jpg","type":"image\/jpeg","tmp_name":"\/tmp\/phpzdiaXV","error":0,"size":1749244}',
'FileStorage' => []
];
$fileMeta = json_decode($file['meta']);
var_dump($fileMeta->name);
The output obviously is:
string(12) "IMAG0161.jpg"
In newer version of PHP you can simplify this: you do not have to store the decoded object in an explicit variable but can directly access the property:
json_decode($file['meta'])->name
The output of this obviously is the same as above.
This is happening because your meta is a json, so you should decode and then access whatever you need, not that I placed true as second parameter becuase i wanted to decode as an associative array instead of an object
$decoded = json_decode($file['meta'],true);
echo $decoded['name'];
//print IMAG0161.jpg
You can check a live demo here
But you can easily access as an obect
$decoded = json_decode($file['meta']);
echo $decoded->name;
//print IMAG0161.jpg
You can check a live demo here
<?php
$file=array(
'uid' => '52',
'guarantee_id' => '1116',
'file_id' => '8',
'file_category' => 'test',
'meta' =>'{"name":"IMAG0161.jpg","type":"image\/jpeg","tmp_name":"\/tmp\/phpzdiaXV","error":0,"size":1749244}',
'FileStorage' => array()
);
$meta=$file['meta'];
$json=json_decode($meta);
echo $json->name;
?>

php make a json object not working as expected

This is my code:
$amenitiesObject = array('parameter-amenities' => array('value' => $amenities));
$buildingObject = array('parameter-building' => array('value' => $building));
$data = array($amenitiesObject, $buildingObject);
$post_data = json_encode($data, JSON_FORCE_OBJECT);
return $post_data;
the result is:
{"0":{"parameter-amenities":{"value":""}},"1":{"parameter-building":{"value":""}}}
while i was hoping for this:
{"parameter-amenities":{"value":""},"parameter-building":{"value":""}}
what is my mistake please?
While #fusion3k's comment is correct and doing $data = array_merge( $amenitiesObject, $buildingObject ); fixes it, I'd like to explain it a little further so you can avoid this type of scenario.
When you do $data = array($amenitiesObject, $buildingObject);, you are not creating a merge of both arrays, you are creating an array with index 0 equals to $amenitiesObject and index 1 equals to $buildingObject, the equivalent of doing :
array(0 => $amenitiesObject, 1 => $buildingObject);
So the json_encode part is working as expected.
When you use array_merge, you maintain only ONE array, that is a combination on both arrays, so you have the expected result.

How can I fix this error about stdClass in PHP

This is my code:
$array = array(
"Birds" =>
array(
'group' => 1,
"Bird" => array(
array('id' => 1, 'img' => "img1.png", 'title' => "kate"),
array('id' => 2, 'img2' => "img2.png", 'title' => "mary")
)) );
$json = json_encode($array);
echo json_decode($json);
OUTPUT IS:
//JSON OUTPUT {"Birds":{"group":1,"Bird":[{"id":1,"img":"img1.png","title":"cardinal"},{"id":2,"img2":"img2.png","title":"bluejay"}]}}
Object of class stdClass could not be converted to string
try
var_dump($json);
This allows you to print out the details of objects and other non-primative types.
Echoing is used for strings - Your json decoded string will be an object of type stdClass
See var_dump http://php.net/manual/en/function.var-dump.php
See echo http://php.net/manual/en/function.echo.php
You have to pass the second parameter of json_decode as true, more info about these parameters at: http://php.net/manual/en/function.json-decode.php
so your echo json_decode($json); should be changed to this:
print_r(json_decode($json, true));
echo is changed to print_r since the output is an array not a string ...
Use var_dump to view variables echo converts your variable to string, while it's object. Also you can add second param to json_decode($data, true) to get array instead object, as i assume that's what you want, because input is array.
About object convertion to string you can read __toString

Categories