I am having a hard time removing a record in my .json file by id.
So my original JSON looks like this:
[["{\"id\":1474753066818,\"name\":\"dd\",\"brand\":\"dd\",\"price\":\"12\"}"],["{\"id\":1474753069035,\"name\":\"dd3\",\"brand\":\"dd\",\"price\":\"12\"}"]]
And this is my php:
<?php
$string = file_get_contents("products.json");
//var_dump($string);
$input = json_decode($string, true);
$output = array();
//here starts the problem
foreach($input as $element) {
if($_GET['data'] != $element[0]["id"]){ //add in array if id doesn't match
$output[] = $element;
}
}
$final = json_encode($output);
$f = #fopen("products.json", "r+");
if ($f !== false) {
ftruncate($f, 0);
fclose($f);
}
file_put_contents("products.json", $final);
>
Basically my problem starts in the foreach where I am iterating through something that looks like this :
array(2) { [0]=> array(1) { [0]=> string(58) "{"id":1474753066818,"name":"dd","brand":"dd","price":"12"}" } [1]=> array(1) { [0]=> string(59) "{"id":1474753069035,"name":"dd3","brand":"dd","price":"12"}" } }
Obviously here I am not able to access the id like I am trying to do in the foreach, because the whole thing is a string.
I have no idea how can I turn this string to an array, compare the id's and then encode it back to my original json format shown at the begining of this post.
Please help!
Your products.json file is a little strange, see below:
[
[
"{\"id\":1474753066818,\"name\":\"dd\",\"brand\":\"dd\",\"price\":\"12\"}"
],
[
"{\"id\":1474753069035,\"name\":\"dd3\",\"brand\":\"dd\",\"price\":\"12\"}"
]
]
Your products.json contains an array of arrays with 1 element whose value is a json encoded string. It looks like you will have to call json_decode again on the string contents to get what you're after.
foreach($input as $element) {
$product = json_decode($element[0]);
if($_GET['data'] != $product["id"]){
//add in array if id doesn't match
$output[] = $product ;
}
}
It's also important to note that the rest of your code:
$final = json_encode($output);
$f = #fopen("products.json", "r+");
if ($f !== false) {
ftruncate($f, 0);
fclose($f);
}
file_put_contents("products.json", $final);
Will not ending up saving the products.json in the same way that you are currently reading it. With the code I provided above it will probably end up looking like this:
[
{"id":1474753066818,"name":"dd","brand":"dd","price":"12"},
{"id":1474753069035,"name":"dd3","brand":"dd","price":"12"}
]
Related
I been looking around and came across array_merge() and json_decode().
I have code were it looks through a file and loops through each line that then pushes that data into a search to pull back information (the information returns as json output.)
File contents:
spotify:track:2SZy40PLDk3vFucXUGFCFA
spotify:track:1ZQnV7ePl8yXoLjPfhWE5L
spotify:track:4NbvIwYcwx8dNGYfUX2bKB
Echoed Output:
{"type":"track","artist":"Jax Jones, Raye","title":"You Don't Know Me","album":"You Don't Know Me","duration":214000,"offset":0,"available":true,"popularity":88} {"type":"track","artist":"MK, Becky Hill","title":"Piece of Me","album":"Piece of Me","duration":189000,"offset":0,"available":true,"popularity":65} {"type":"track","artist":"Wankelmut, Emma Louise","title":"My Head Is A Jungle - MK Remix / Radio Edit","album":"My Head Is A Jungle (MK Remix / Radio Edit)","duration":205000,"offset":0,"available":true,"popularity":62}
I want to merge all that data into one json thats called tracks, something like {"tracks":[{" and inside have the json information.
My Code:
$contents = '';
$dataarray = file('/location/'.$_GET['playlist'].''); //Push file data into array
$finallist = '';
//Grab Track Info
//echo count($dataarray);
foreach ($dataarray as $line_num => $line) //Loop Through Data
{
$line = str_replace("\n", "", $line); //Replace new line on string
$contents = searchCommand($connect, 'uinfo '.$line); //Returns Json for that single track
if (stripos($contents, '"error":"invalid argument (should be a Spotify URI)"') == FALSE && stripos($contents, '"error": "invalid command"') == FALSE) //If we found tracks
{
echo $contents;
}
else
{
echo "Fail";
}
}
I created an array and converted it to json and so i can read it via JS.
foreach ($dataarray as $line_num => $line) //Loop Through Data
{
$line = str_replace("\n", "", $line); //Replace new line on string
$contents = searchSpopCommand($spop, 'uinfo '.$line); //Returns Json for that single track
if (stripos($contents, '"error":"invalid argument (should be a Spotify URI)"') == FALSE && stripos($contents, '"error": "invalid command"') == FALSE) //If we found tracks
{
$finallist .= $contents;
}
else
{
echo "Fail";
}
}
$array = explode("\n", $finallist);
array_pop($array);
echo json_encode($array);
Would of been ideal if i can give it a name though!
I am trying to convert CSV file to JSON using PHP.
Here is my code
<?php
date_default_timezone_set('UTC');
$today = date("n_j"); // Today is 1/23/2015 -> $today = 1_23
$file_name = $today.'.CSV'; // My file name is 1_23.csv
$file_path = 'C:\\Users\\bheng\\Desktop\\qb\\'.$file_name;
$file_handle = fopen($file_path, "r");
$result = array();
if ($file_handle !== FALSE) {
$column_headers = fgetcsv($file_handle);
foreach($column_headers as $header) {
$result[$header] = array();
}
while (($data = fgetcsv($file_handle)) !== FALSE) {
$i = 0;
foreach($result as &$column) {
$column[] = $data[$i++];
}
}
fclose($file_handle);
}
// print_r($result); // I see all data(s) except the header
$json = json_encode($result);
echo $json;
?>
print_r($result); // I see all data(s)
Then I json_encode($result); and tried to display it, but nothing is displaying on the screen at all. All I see is the blank screen, and 0 error message.
Am I doing anything wrong ? Can someone help me ?
Added Result of print_r($result);
Array (
[Inventory] => Array (
[0] => bs-0468R(20ug)
[1] => bs-1338R(1ml)
[2] => bs-1557G(no bsa)
[3] => bs-3295R(no BSA)
[4] => bs-0730R-Cy5"
[5] => bs-3889R-PE-Cy7"
[6] => 11033R
[7] => 1554R-A647
[8] => 4667
[9] => ABIN731018
[10] => Anti-DBNL protein
.... more ....
Try like this:
$file="1_23.csv";
$csv= file_get_contents($file);
$array = array_map("str_getcsv", explode("\n", $csv));
$json = json_encode($array);
print_r($json);
data.csv
Game,Skill
Treasure Hunter,pilipala
Rocket Launcher,bibobibo
Rocket Engine,hehehohoho
To convert with column name, this is how I do it.
csv2json.php
<?php
if (($handle = fopen("data.csv", "r")) !== FALSE) {
$csvs = [];
while(! feof($handle)) {
$csvs[] = fgetcsv($handle);
}
$datas = [];
$column_names = [];
foreach ($csvs[0] as $single_csv) {
$column_names[] = $single_csv;
}
foreach ($csvs as $key => $csv) {
if ($key === 0) {
continue;
}
foreach ($column_names as $column_key => $column_name) {
$datas[$key-1][$column_name] = $csv[$column_key];
}
}
$json = json_encode($datas);
fclose($handle);
print_r($json);
}
The output result
[
{
"Game": "Treasure Hunter",
"Skill": "pilipala"
},
{
"Game": "Rocket Launcher",
"Skill": "bibobibo"
},
{
"Game": "Rocket Engine",
"Skill": "hehehohoho"
}
]
You can try this way too.
<?php
function csvtojson($file,$delimiter)
{
if (($handle = fopen($file, "r")) === false)
{
die("can't open the file.");
}
$csv_headers = fgetcsv($handle, 4000, $delimiter);
$csv_json = array();
while ($row = fgetcsv($handle, 4000, $delimiter))
{
$csv_json[] = array_combine($csv_headers, $row);
}
fclose($handle);
return json_encode($csv_json);
}
$jsonresult = csvtojson("./doc.csv", ",");
echo $jsonresult;
I ran into a similar problem, I ended up using this to recursively convert the data to UTF-8 on an array before encoding to JSON.
function utf8_converter($array)
{
array_walk_recursive($array, function(&$item, $key){
if(!mb_detect_encoding($item, 'utf-8', true)){
$item = utf8_encode($item);
}
});
return $array;
}
From:
http://nazcalabs.com/blog/convert-php-array-to-utf8-recursively/
This issue is pretty old by now, but hoping this helps someone, as it seemed like the simplest example I found, and I know this is a pretty common thing devs might need to do as a beginner, and lots of answers gloss over the magic.
$file = storage_path('app/public/waitlist_users_test.csv'); //--> laravel helper, but you can use any path here
function csv_to_json($file)
{
// file() loads each row as an array value, then array map uses the 'str_getcsv' callback to
$csv = array_map('str_getcsv', file($file));
// array_walk - "walks" through each item of the array and applies the call back function. the & in "&row" means that alterations to $row actually change the original $csv array, rather than treating it as immutable (*sort of immutable...)
array_walk($csv, function(&$row) use ($csv) {
// array_combine takes the header row ($csv[0]) and uses it as array keys for each column in the row
$row = array_combine($csv[0], $row);
});
array_shift($csv); # removes now very redundant column header --> contains {'col_1':'col_1', 'col_2':'col_2'...}
$json = json_encode($csv);
return $json;
}
There's a lot of magic going on with these functions that accept callback functions, that didn't seem to be explained thoroughly above. I'm self taught and have been programming for years, and find that it's often just glossed over without detailing how callbacks work, so I'll dive in just a little bit for the array_map('str_getcsv', file($file)) function - if you pass a function you've written, or inbuilt php function name as a string, it will take the value of whatever (in this case - array) element is being evaluated by the calling function (in this case array_map), and pass that to the callback function without the need to explicitly pass in a variable - super helpful once you get the hang of it, but I find it's not explained thoroughly very often which leaves beginners to not understand why it works, just that it works.
I've linked most of these above, but here's a little more information:
str-getcsv do? Array Walk Array Map Callables/Callbacks
as #MoonCactus noted, the file() function only loads 1 row at a time which helps save on memory usage for large .csv files.
Also, some other posts reference using explode - why not use explode() instead of str_getcsv() to parse rows? Because explode() would not treat possible enclosured parts of string or escaped characters correctly.
Hope somebody finds this helpful!
If you are converting a dynamic CSV file, you can pass the URL through a parameter (url=http://example.com/some.csv) and it will show you the most up-to-date version:
<?php
// Lets the browser and tools such as Postman know it's JSON
header( "Content-Type: application/json" );
// Get CSV source through the 'url' parameter
if ( isset( $_GET['url'] ) ) {
$csv = explode( "\n", file_get_contents( $_GET['url'] ) );
$index = str_getcsv( array_shift( $csv ) );
$json = array_map(
function ( $e ) use ( $index ) {
return array_combine( $index, str_getcsv( $e ) );
}, $csv
);
}
else {
$json = "Please set the path to your CSV by using the '?url=' query string.";
}
// Output JSON
echo json_encode( $json );
Alternate solution that uses similar method as #Whirlwind's solution but returns a more standard JSON result (with named fields for each object/record):
// takes a string of CSV data and returns a JSON representing an array of objects (one object per row)
function convert_csv_to_json($csv_data){
$flat_array = array_map("str_getcsv", explode("\n", $csv_data));
// take the first array item to use for the final object's property labels
$columns = $flat_array[0];
for ($i=1; $i<count($flat_array)-1; $i++){
foreach ($columns as $column_index => $column){
$obj[$i]->$column = $flat_array[$i][$column_index];
}
}
$json = json_encode($obj);
return $json; // or just return $obj if that's a more useful return value
}
The accepted answer uses file_get_contents() to read the entire file as a string in memory, and then explode() it to make it an array.
But it can be made faster, smaller in memory, and more useful:
function ReadCsv($fn)
{
$lines= file($fn); // read file directly as an array of lines
array_pop($lines); // you can remove the last empty line (if required)
$json= json_encode(array_map("str_getcsv", $lines), JSON_NUMERIC_CHECK);
print_r($json);
}
Nb: I used JSON_NUMERIC_CHECK here to avoid numbers being double quoted into strings. It also reduces the output size and it usually helps javascript on the other side (e.g. to compute or plot the data). Beware of phone numbers though!
I liked #ian-d-miller's solution for converting the data into a key / value style format, but I kept running into issues with his code.
Here's what worked for me:
function convert_CSV_to_JSON($csv_data){
// convert csv data to an array
$data = array_map("str_getcsv", explode("\n", $csv_data));
// use the first row as column headers
$columns = $data[0];
// create array to hold our converted data
$json = [];
// iterate through each row in the data
foreach ($data as $row_index => $row_data) {
// skip the first row, since it's the headers
if($row_index === 0) continue;
// make sure we establish each new row as an array
$json[$row_index] = [];
// iterate through each column in the row
foreach ($row_data as $column_index => $column_value) {
// get the key for each entry
$label = $columns[$column_index];
// add this column's value to this row's index / column's key
$json[$row_index][$label] = $column_value;
}
}
// bam
return $json;
}
Usage:
// as is
$json = convert_CSV_to_JSON($csv);
// encoded
$json = json_encode($json);
Something that i've made for myself and may be useful for others :)
This will convert CSV into JSON array with objects (key => value pair).
function csv2json($a, $e = true) {
$b = ["\r\n","\r","\n",];
foreach ($b as $c => $d) {
$a = explode($d, $a);
$a = isset($b[$c + 1]) ? implode($b[$c + 1], $a) : implode(PHP_EOL, $a);
}
// Convert to CSV
$a = array_map("str_getcsv", explode(PHP_EOL, $a));
// Get the first part of the array as the keys
$a = [
"keys" => array_shift($a),
"rows" => $a,
"row" => null,
];
// Define JSON
$b = [];
foreach ($a["rows"] as $a["row"]) {
$a["row"] = [ "csv" => $a["row"], "json" => (object)[], ];
for ($c = 0; $c < count($a["row"]["csv"]); $c++) {
$a["row"]["csv"][$c] = [#json_decode($a["row"]["csv"][$c]),$a["row"]["csv"][$c]];
// Switch from string to booleans, numbers and others
$a["row"]["csv"][$c] = isset($a["row"]["csv"][$c][0]) ? $a["row"]["csv"][$c][0] : $a["row"]["csv"][$c][1];
// Push it back
$a["row"]["json"]->{$a["keys"][$c]} = $a["row"]["csv"][$c];
}
$a["row"] = $a["row"]["json"];
$b[] = $a["row"];
unset($a["row"]);
}
// $e will be "return"
$e = $e ? json_encode($b) : $b;
// Unset useless variables
unset($a, $b, $c, $d);
return $e;
}
How to use?
If you want to return the JSON as a string, Leave it as default.
If you want to return the JSON as an object / array, set the second parameter to false.
Examples:
$csv = "name,age,gender
John Doe,35,male
Jane Doe,32,female";
echo csv2json($csv, true); // Or without the second parameter, just csv2json($csv)
The example above (^) will return a JSON stringified, Like this:
[{"name":"John Doe","age":35,"gender":"male"},{"name":"Jane Doe","age":32,"gender":"female"}]
and the example below:
var_dump(csv2json($csv, false));
will return a JSON array with these objects:
array(2) {
[0]=>
object(stdClass)#1 (3) {
["name"]=>
string(8) "John Doe"
["age"]=>
int(35)
["gender"]=>
string(4) "male"
}
[1]=>
object(stdClass)#2 (3) {
["name"]=>
string(8) "Jane Doe"
["age"]=>
int(32)
["gender"]=>
string(6) "female"
}
}
public function CsvToJson($fileContent){
//Convert CSV To Json and Return
$all_rows = array();
$newhead =array();
//Extract csv data to array on \n
$array = explode("\n",$fileContent);
//Extract csv header to array on 0 Index
$header = explode(",",$array[0]);
//Remove Header Row From Main Data Array
array_shift($array);
//Extract All Arrays To Saperate Orders
foreach($array as $arr){
$sliced = explode(",",$arr);
array_push($all_rows,$sliced);
}
//Extract All Orders Element To Saperate Array Item
foreach($all_rows as $row){
$sliced = explode(",",$arr);
array_push($all_rows,$sliced);
}
//Remove \r From Header Elements
foreach($header as $key=>$value){
$sliced = str_replace ("\r", "", $value);
array_push($newhead,$sliced);
}
//COMBINE Header as KEY And Row Element As Value
$arrrr = array();
foreach($all_rows as $row) {
//Remove Last Element of ROW if it is \r (Break given in css file for next row)
$count= count($row);
if ($row[$count-1] == "\r") {
array_splice($row, count($row) - 1, 1);
}
//CHECK IF HADER COUNT == ROW COUNT
if (count($header) == count($row)) {
array_push($arrrr,array_combine($newhead,$row));
}
}
//CONVERT ARRAY TO JSON
$json = json_encode($arrrr);
//Remove backslasesh from json key and and value to remove \r
$clean = stripslashes($json);
//CONVERT ARRAY TO JSON AGAIN FOR EXPORT
$jsonagain = json_encode($clean);
return $jsonagain;
}
I have a file called "single.txt". The contents look like:
Array ( [0] => Ada Lovelace,F,96,ISTJ,Linux,24,99
[1] => Adele Goldberg,F,65,ENFJ,Windows,50,70
[2] => Alan Turing,M,41,ESTP,Mac OS X,31,50...
)
First, when a new person signs up, it adds them with them with their info to the end of the .txt file. I want to be able to check whether they've already signed up and I've written the following function:
function returnPerson($content){
global $person_name;
for($i=0 ; $i < count($content); $i++){
if($person_name == array_slice($content,0,0)){
$person = $content[$i];
return $person;
} else continue;
}
}
But that doesn't seem to be working.
How can I compare the first part of the string, i.e. the name part, to the name of the person checking?
Thanks!
Try something like this... you may have to modify it slightly depending on how your text is coming in, but should get you on the right track :)
function returnPerson($content){
global $person_name;
foreach($content as $profile) {
$profile = explode(',', $profile);
if ($person_name == $profile[0]) {
// Person Exists
return $profile;
}
}
return false; // person does not exist
}
You're "slicing" the same array while you're looping it. It looks like you just need a simple strpos():
if(strpos($content[$i], $person . ',') === 0){
return ...
}
Here's another way that doesn't require a for loop:
$names = array_map('reset', array_map('str_getcsv', $content));
if(in_array($person, $names)){
...
}
It works because your data seems to use the CSV format
You can loop over the elements in the array like this:
foreach ($content as $record) {
// $record now contains string "Ada Lovelace,F,96,ISTJ,Linux,24,99"
}
You can extract fields from a comma-separated string by using the explode() function:
$string = "Ada Lovelace,F,96,ISTJ,Linux,24,99";
$fields = explode(',', $string);
// $fields[0] now contains "Ada Lovelace"
// $fields[1] now comtains "F"
// ... etc
Putting those together, you'll get something like:
foreach ($content as $record) {
$fields = explode(',', $record);
if ($fields[0] == $name_to_check) {
// found it
}
}
// didn't find it
I have a really broken/weird INI file that looks like this.
RowID=11668
Name=SCNA DaCe
PPA
Relation=Family
RowID=31999
Name=PCA
RowID=11593
Name=CRMLEVEL
Relation=Family
If possible, end up as
array("11668" => array("name"=> "SCNA DaCe", "relation"=>"Family", "ppa"=>true));
Linebreaks are separated based on RowID instead of a proper [section] and I have no idea how I can read this, any tips on where to start?
There is inconsistent casing, certain things don't have values (like PPA by itself on a line), not all key=vals are defined for each case.
For something like this, an array of objects comes in handy.
http://www.laprbass.com/RAY_temp_dylan.php
<?php // RAY_temp_dylan.php
error_reporting(E_ALL);
echo '<pre>';
$str = <<<END
RowID=11668
Name=SCNA DaCe
PPA
Relation=Family
RowID=31999
Name=PCA
RowID=11593
Name=CRMLEVEL
Relation=Family
END;
// SIMULATE READING WITH file()
$arr = explode(PHP_EOL, $str);
// COLLECT THE NORMALIZED DATA HERE
$out = array();
$obj = new stdClass;
// USE AN ITERATOR ON EACH ROW
foreach ($arr as $row)
{
// SKIP BLANK LINES
$row = trim($row);
if (empty($row)) continue;
// FOR EACH ROWID CREATE A NEW OBJECT
if (FALSE !== strpos($row, 'RowID'))
{
// SAVE THE OLD OBJECT
$out[] = $obj;
$obj = new stdClass;
$obj->RowID = end(explode('=', $row));
}
// FOR REMAINING ELEMENTS THAT ARE KEY-VALUE PAIRS
if (FALSE !== strpos($row, '='))
{
$key = current(explode('=', $row));
$val = end(explode('=', $row));
$obj->$key = $val;
}
// FOR REMAINING ELEMENTS THAT ARE NOT KEY-VALUE PAIRS
else
{
$obj->$row = TRUE;
}
}
// SAVE LAST ELEMENT AT EOF
$out[] = $obj;
// DISCARD THE ZERO "STARTER" ELEMENT
unset($out[0]);
var_dump($out);
You would have to roll your own custom solution to parse this INI file as PHP's built in parse_ini_file is based on PHP's own php.ini format constraints. So it has to be valid PHP.
For your purposes if the requirements are as simple as key/value pairs on each line with the exception of the one-off stranded value as a default boolean true then you could do something like the following.
function my_parse_ini($ini_file_name) {
$ini = file($ini_file_name, FILE_IGNORE_NEW_LINES);
$return = array();
$row = null;
foreach ($ini as $key => $value) {
if ($value == '') {
$row = null;
continue;
}
#list($k, $v) = explode('=',$value);
if ($v === null) {
$v = true;
}
if ($row === null) {
$row = $v;
$return[$row] = array();
continue;
}
$return[$row][$k] = $v;
}
return $return;
}
/* usage */
var_dump(my_parse_ini('test.ini'));
This would output the following for your sample ini file....
array(2) {
[11668]=>
array(4) {
["Name"]=>
string(3) "PCA"
["PPA"]=>
bool(true)
["Relation"]=>
string(6) "Family"
["RowID"]=>
string(5) "31999"
}
[11593]=>
array(2) {
["Name"]=>
string(8) "CRMLEVEL"
["Relation"]=>
string(6) "Family"
}
}
Hello I am performing a query with the paypal API and my question concerns an array and retrieving values for the key (which is dynamic) I know the query works and credentials are good, as the following array is returned:
array(2) {
["L_TRANSACTIONID0"]=>
string(17) "9FX81733DJ079610B"
["L_TRANSACTIONID1"]=>
string(17) "5E083945JC6368706"
["L_TRANSACTIONID2"]=>
string(17) "7SP75180Y9281954W"
}
I am wanting to break each key out in a foreach loop, but each key is dynamic (notice the count on each key).
How can this be accomplished in a foreach loop?
Thanks,
I just answered a similar question the other day, so potentially a duplicate. In any case, if this helps someone, here goes:
function process_response($str)
{
$data = array();
$x = explode("&", $str);
foreach($x as $val)
{
$y = explode("=", $val);
preg_match_all('/^([^\d]+)(\d+)/', $y[0], $match);
if (isset($match[1][0]))
{
$text = $match[1][0];
$num = $match[2][0];
$data[$num][$text] = urldecode($y[1]);
}
else
{
$text = $y[0];
// $data[$text] = urldecode($y[1]);
}
}
return $data;
}
Just feed the result from your curl call into this and take the result as a formatted array.
Note the commented out line, there are some fields that are global, such as version, if you want these, uncomment, but then you may have to adjust some formatting code down stream.
As an example of how to use this, say you want to feed this into PHPExcel object, you could do so like so:
$response = your_curl_call($request);
$data = process_response($response);
$index = 1;
foreach($data as $row)
{
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$index, $row['L_TIMESTAMP'])
->setCellValue('B'.$index, $row['L_TIMEZONE'])
->setCellValue('C'.$index, $row['L_TYPE'])
->setCellValue('D'.$index, $row['L_EMAIL'])
->setCellValue('E'.$index, $row['L_NAME'])
->setCellValue('F'.$index, $row['L_TRANSACTIONID'])
->setCellValue('G'.$index, $row['L_STATUS'])
->setCellValue('H'.$index, $row['L_AMT'])
->setCellValue('I'.$index, $row['L_CURRENCYCODE'])
->setCellValue('J'.$index, $row['L_FEEAMT'])
->setCellValue('K'.$index, $row['L_NETAMT']);
$index++;
}