JSON Array convert to CSV2019 Community Moderator ElectionCreate ArrayList from arrayHow do I check if an array includes an object in JavaScript?Can comments be used in JSON?How to append something to an array?PHP: Delete an element from an arrayWhat is the correct JSON content type?Why does Google prepend while(1); to their JSON responses?Loop through an array in JavaScriptHow do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?

Why is a white electrical wire connected to 2 black wires?

What options are left, if Britain cannot decide?

Bach's Toccata and Fugue in D minor breaks the "no parallel octaves" rule?

Why one should not leave fingerprints on bulbs and plugs?

PTIJ: Halachic Status of Breadboards on Pesach

How to pronounce "I ♥ Huckabees"?

This word with a lot of past tenses

How are passwords stolen from companies if they only store hashes?

How to get the n-th line after a grepped one?

Describing a chess game in a novel

Is it true that good novels will automatically sell themselves on Amazon (and so on) and there is no need for one to waste time promoting?

Why is the President allowed to veto a cancellation of emergency powers?

Explaining pyrokinesis powers

A single argument pattern definition applies to multiple-argument patterns?

What's the meaning of a knight fighting a snail in medieval book illustrations?

Min function accepting varying number of arguments in C++17

How to write cleanly even if my character uses expletive language?

Are Roman Catholic priests ever addressed as pastor

Brexit - No Deal Rejection

Why do newer 737s use two different styles of split winglets?

ERC721: How to get the owned tokens of an address

Math equation in non italic font

Is "upgrade" the right word to use in this context?

Most cost effective thermostat setting: consistent temperature vs. lowest temperature possible



JSON Array convert to CSV



2019 Community Moderator ElectionCreate ArrayList from arrayHow do I check if an array includes an object in JavaScript?Can comments be used in JSON?How to append something to an array?PHP: Delete an element from an arrayWhat is the correct JSON content type?Why does Google prepend while(1); to their JSON responses?Loop through an array in JavaScriptHow do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?










0















I'm trying to convert a JSON response to CSV file but I have a problem about arrays
Here is the conversion code to CSV



$jsonString = file_get_contents("feed.json");
$jsonDecoded = json_decode($jsonString, true);
$json = $jsonDecoded['results'];
jsonToCsv($json, "feed.csv");

function jsonToCsv ($json, $csvFilePath = false, $boolOutputFile = false)

// See if the string contains something
if (empty($json))
die("The JSON string is empty!");


// If passed a string, turn it into an array
if (is_array($json) === false)
$json = json_decode($json, true);


// If a path is included, open that file for handling. Otherwise, use a temp file (for echoing CSV string)
if ($csvFilePath !== false)
$f = fopen($csvFilePath,'w+');
if ($f === false)
die("Couldn't create the file to store the CSV, or the path is invalid. Make sure you're including the full path, INCLUDING the name of the output file (e.g. '../save/path/csvOutput.csv')");


else
$boolEchoCsv = true;
if ($boolOutputFile === true)
$boolEchoCsv = false;

$strTempFile = 'feed' . date("U") . ".csv";
$f = fopen($strTempFile,"w+");


$firstLineKeys = false;
foreach ($json as $line)
if (empty($firstLineKeys))
$firstLineKeys = array_keys($line);
fputcsv($f, $firstLineKeys);
$firstLineKeys = array_flip($firstLineKeys);


// Using array_merge is important to maintain the order of keys acording to the first element
fputcsv($f, array_merge($firstLineKeys, $line));

fclose($f);

// Take the file and put it to a string/file for output (if no save path was included in function arguments)
if ($boolOutputFile === true)
if ($csvFilePath !== false)
$file = $csvFilePath;

else
$file = $strTempFile;


// Output the file to the browser (for open/save)
if (file_exists($file))
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Length: ' . filesize($file));
readfile($file);


elseif ($boolEchoCsv === true)
if (($handle = fopen($strTempFile, "r")) !== FALSE)
while (($data = fgetcsv($handle)) !== FALSE)
echo implode(",",$data);
echo "<br />";

fclose($handle);



// Delete the temp file
unlink($strTempFile);


?>


And here is a example of feed.json content



 
"isError":false,
"messages":[

],
"results":[

"part_number_key":"DASDSA",
"buy_button_rank":1,
"category_id":11,
"id":123,
"brand":"brand",
"vendor_category_id":null,
"name":"Name",
"part_number":"part number",
"sale_price":12.31,
"currency":"RON",
"description":"description",
"url":"https://www.url.com",
"warranty":12,
"general_stock":10,
"weight":"0",
"status":1,
"recommended_price":12.19,
"images":[

"url":"https://url.com/images.jpg1",
"display_type":1
,

"url":"https://url.com/images.jpg2",
"display_type":0
,

"url":"https://url.com/images.jpg3",
"display_type":0

],
"characteristics":[

"id":8937,
"value":"value"
,

"id":8930,
"value":"value"
,

"id":8927,
"value":"value"
,

"id":8928,
"value":"value"
,

"id":5537,
"value":"value"
,

"id":8932,
"value":"value"
,

"id":8934,
"value":"value"
,

"id":8929,
"value":"value"
,

"id":7235,
"value":"value"
,

"id":6556,
"value":"value"
,

"id":5401,
"value":"value"

],
"attachments":[

],
"vat_id":1,
"family":
"id":1104,
"name":"NAME",
"family_type_id":244
,
"start_date":[

],
"estimated_stock":10,
"reversible_vat_charging":false,
"min_sale_price":11,
"max_sale_price":200,
"offer_details":
"id":2484194,
"warranty_type":null,
"supply_lead_time":14
,
"offer_properties":[

],
"product_measurements":[

],
"availability":[

"warehouse_id":1,
"id":3

],
"stock":[

"warehouse_id":1,
"value":10

],
"handling_time":[

"warehouse_id":1,
"value":0

],
"barcode":[

],
"ean":[

],
"commission":
"value":"20.0000",
"type":"percentage",
"id":"123",
"priority":"4",
"created":"2010-01-16 11:25:02"
,
"validation_status":[

"value":9,
"description":"Approved documentation",
"errors":null

],
"offer_validation_status":
"value":1,
"description":"Saleable",
"errors":null
,
"ownership":1,
"best_offer_sale_price":11,
"best_offer_recommended_price":11,
"number_of_offers":1
,

"part_number_key":"D3129DKQW",
"buy_button_rank":1,
"category_id":456,
"id":123,
"brand":"Bluedio",
"vendor_category_id":null,
"name":"name",
"part_number":"part number",
"sale_price":123,
"currency":"EUR",
"description":"description",
"url":"https://url.com",
"warranty":24,
"general_stock":1,
"weight":"0",
"status":1,
"recommended_price":12,
"images":[

"url":"https://url.com/images.jpg1",
"display_type":1
,

"url":"https://url.com/images.jpg2",
"display_type":0
,

"url":"https://url.com/images.jpg3",
"display_type":0

],
"characteristics":[

"id":7774,
"value":"val"
,

"id":7947,
"value":"val"
,

"id":8001,
"value":"val"
,

"id":8937,
"value":"val"
,

"id":8930,
"value":"val"
,

"id":8927,
"value":"val"
,

"id":8928,
"value":"val"
,

"id":5537,
"value":"val"
,

"id":8932,
"value":"val"
,

"id":8934,
"value":"val"
,

"id":8929,
"value":"val"
,

"id":7235,
"value":"val"
,

"id":6556,
"value":"val"
,

"id":5401,
"value":"val"

],
"attachments":[

],
"vat_id":1,
"family":
"id":123456,
"name":"Name",
"family_type_id":244
,
"start_date":[

],
"estimated_stock":144,
"reversible_vat_charging":false,
"min_sale_price":11,
"max_sale_price":200,
"offer_details":
"id":242414,
"warranty_type":null,
"supply_lead_time":14
,
"offer_properties":[

],
"product_measurements":[

],
"availability":[

"warehouse_id":1,
"id":3

],
"stock":[

"warehouse_id":1,
"value":9

],
"handling_time":[

"warehouse_id":1,
"value":0

],
"barcode":[

],
"ean":[

],
"commission":
"value":"20.0000",
"type":"percentage",
"id":"12492",
"priority":"4",
"created":"2010-01-16 11:25:02"
,
"validation_status":[

"value":9,
"description":"Approved documentation",
"errors":null

],
"offer_validation_status":
"value":1,
"description":"Saleable",
"errors":null
,
"ownership":1,
"best_offer_sale_price":77.31,
"best_offer_recommended_price":83.19,
"number_of_offers":1

]



Here is the output of the conversion



part_number_key,buy_button_rank,category_id,id,brand,vendor_category_id,name,part_number,sale_price,currency,description,url,warranty,general_stock,weight,status,recommended_price,images,characteristics,attachments,vat_id,family,start_date,estimated_stock,reversible_vat_charging,min_sale_price,max_sale_price,offer_details,offer_properties,product_measurements,availability,stock,handling_time,barcode,ean,commission,validation_status,offer_validation_status,ownership,best_offer_sale_price,best_offer_recommended_price,number_of_offers
DASDSA,1,11,123,brand,,Name,"part number",12.31,RON,description,https://www.url.com,12,10,0,1,12.19,Array,Array,Array,1,Array,Array,10,,11,200,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,1,11,11,1
D3129DKQW,1,456,123,Bluedio,,name,"part number",123,EUR,description,https://url.com,24,1,0,1,12,Array,Array,Array,1,Array,Array,144,,11,200,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,1,77.31,83.19,1


As you can see, there is array instead of values, can someone tell me why?



I tried reset() function but I get only the value from the first column ( part_number_key )



foreach ($json as $line) 
if (empty($firstLineKeys))
$firstLineKeys = array_keys($line); print_r("aici3"); fputcsv($f,
$firstLineKeys); print_r("aici3"); $firstLineKeys = array_flip($firstLineKeys);
fputcsv($f,
array_merge($firstLineKeys,
$line)); $first = reset($line); print_r($first);



I want to extract all columns but to show only the first row value from every from every column, for example at "images" column I would like to extract just the first url and same for the rest of columns



And one more thing, what is the best method to ignore few columns?



Thanks in advance!










share|improve this question
























  • Because the images and characteristics, etc, are arrays. If you want to get the values, you'll have to pull that data out individually as well.

    – aynber
    Mar 7 at 15:42











  • How would the result look for multiple values in the inner array?

    – Nico Haase
    Mar 7 at 15:44











  • @Nico Haase The best way would be to extract the first value but I don't know how...

    – cristi alexandru
    Mar 7 at 15:47











  • Well, that would be $array[0] then or reset($array) - but wouldn't you lose a lot of data then?

    – Nico Haase
    Mar 7 at 15:49











  • @cristialexandru - $first = reset($array);

    – ArtisticPhoenix
    Mar 7 at 15:49















0















I'm trying to convert a JSON response to CSV file but I have a problem about arrays
Here is the conversion code to CSV



$jsonString = file_get_contents("feed.json");
$jsonDecoded = json_decode($jsonString, true);
$json = $jsonDecoded['results'];
jsonToCsv($json, "feed.csv");

function jsonToCsv ($json, $csvFilePath = false, $boolOutputFile = false)

// See if the string contains something
if (empty($json))
die("The JSON string is empty!");


// If passed a string, turn it into an array
if (is_array($json) === false)
$json = json_decode($json, true);


// If a path is included, open that file for handling. Otherwise, use a temp file (for echoing CSV string)
if ($csvFilePath !== false)
$f = fopen($csvFilePath,'w+');
if ($f === false)
die("Couldn't create the file to store the CSV, or the path is invalid. Make sure you're including the full path, INCLUDING the name of the output file (e.g. '../save/path/csvOutput.csv')");


else
$boolEchoCsv = true;
if ($boolOutputFile === true)
$boolEchoCsv = false;

$strTempFile = 'feed' . date("U") . ".csv";
$f = fopen($strTempFile,"w+");


$firstLineKeys = false;
foreach ($json as $line)
if (empty($firstLineKeys))
$firstLineKeys = array_keys($line);
fputcsv($f, $firstLineKeys);
$firstLineKeys = array_flip($firstLineKeys);


// Using array_merge is important to maintain the order of keys acording to the first element
fputcsv($f, array_merge($firstLineKeys, $line));

fclose($f);

// Take the file and put it to a string/file for output (if no save path was included in function arguments)
if ($boolOutputFile === true)
if ($csvFilePath !== false)
$file = $csvFilePath;

else
$file = $strTempFile;


// Output the file to the browser (for open/save)
if (file_exists($file))
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Length: ' . filesize($file));
readfile($file);


elseif ($boolEchoCsv === true)
if (($handle = fopen($strTempFile, "r")) !== FALSE)
while (($data = fgetcsv($handle)) !== FALSE)
echo implode(",",$data);
echo "<br />";

fclose($handle);



// Delete the temp file
unlink($strTempFile);


?>


And here is a example of feed.json content



 
"isError":false,
"messages":[

],
"results":[

"part_number_key":"DASDSA",
"buy_button_rank":1,
"category_id":11,
"id":123,
"brand":"brand",
"vendor_category_id":null,
"name":"Name",
"part_number":"part number",
"sale_price":12.31,
"currency":"RON",
"description":"description",
"url":"https://www.url.com",
"warranty":12,
"general_stock":10,
"weight":"0",
"status":1,
"recommended_price":12.19,
"images":[

"url":"https://url.com/images.jpg1",
"display_type":1
,

"url":"https://url.com/images.jpg2",
"display_type":0
,

"url":"https://url.com/images.jpg3",
"display_type":0

],
"characteristics":[

"id":8937,
"value":"value"
,

"id":8930,
"value":"value"
,

"id":8927,
"value":"value"
,

"id":8928,
"value":"value"
,

"id":5537,
"value":"value"
,

"id":8932,
"value":"value"
,

"id":8934,
"value":"value"
,

"id":8929,
"value":"value"
,

"id":7235,
"value":"value"
,

"id":6556,
"value":"value"
,

"id":5401,
"value":"value"

],
"attachments":[

],
"vat_id":1,
"family":
"id":1104,
"name":"NAME",
"family_type_id":244
,
"start_date":[

],
"estimated_stock":10,
"reversible_vat_charging":false,
"min_sale_price":11,
"max_sale_price":200,
"offer_details":
"id":2484194,
"warranty_type":null,
"supply_lead_time":14
,
"offer_properties":[

],
"product_measurements":[

],
"availability":[

"warehouse_id":1,
"id":3

],
"stock":[

"warehouse_id":1,
"value":10

],
"handling_time":[

"warehouse_id":1,
"value":0

],
"barcode":[

],
"ean":[

],
"commission":
"value":"20.0000",
"type":"percentage",
"id":"123",
"priority":"4",
"created":"2010-01-16 11:25:02"
,
"validation_status":[

"value":9,
"description":"Approved documentation",
"errors":null

],
"offer_validation_status":
"value":1,
"description":"Saleable",
"errors":null
,
"ownership":1,
"best_offer_sale_price":11,
"best_offer_recommended_price":11,
"number_of_offers":1
,

"part_number_key":"D3129DKQW",
"buy_button_rank":1,
"category_id":456,
"id":123,
"brand":"Bluedio",
"vendor_category_id":null,
"name":"name",
"part_number":"part number",
"sale_price":123,
"currency":"EUR",
"description":"description",
"url":"https://url.com",
"warranty":24,
"general_stock":1,
"weight":"0",
"status":1,
"recommended_price":12,
"images":[

"url":"https://url.com/images.jpg1",
"display_type":1
,

"url":"https://url.com/images.jpg2",
"display_type":0
,

"url":"https://url.com/images.jpg3",
"display_type":0

],
"characteristics":[

"id":7774,
"value":"val"
,

"id":7947,
"value":"val"
,

"id":8001,
"value":"val"
,

"id":8937,
"value":"val"
,

"id":8930,
"value":"val"
,

"id":8927,
"value":"val"
,

"id":8928,
"value":"val"
,

"id":5537,
"value":"val"
,

"id":8932,
"value":"val"
,

"id":8934,
"value":"val"
,

"id":8929,
"value":"val"
,

"id":7235,
"value":"val"
,

"id":6556,
"value":"val"
,

"id":5401,
"value":"val"

],
"attachments":[

],
"vat_id":1,
"family":
"id":123456,
"name":"Name",
"family_type_id":244
,
"start_date":[

],
"estimated_stock":144,
"reversible_vat_charging":false,
"min_sale_price":11,
"max_sale_price":200,
"offer_details":
"id":242414,
"warranty_type":null,
"supply_lead_time":14
,
"offer_properties":[

],
"product_measurements":[

],
"availability":[

"warehouse_id":1,
"id":3

],
"stock":[

"warehouse_id":1,
"value":9

],
"handling_time":[

"warehouse_id":1,
"value":0

],
"barcode":[

],
"ean":[

],
"commission":
"value":"20.0000",
"type":"percentage",
"id":"12492",
"priority":"4",
"created":"2010-01-16 11:25:02"
,
"validation_status":[

"value":9,
"description":"Approved documentation",
"errors":null

],
"offer_validation_status":
"value":1,
"description":"Saleable",
"errors":null
,
"ownership":1,
"best_offer_sale_price":77.31,
"best_offer_recommended_price":83.19,
"number_of_offers":1

]



Here is the output of the conversion



part_number_key,buy_button_rank,category_id,id,brand,vendor_category_id,name,part_number,sale_price,currency,description,url,warranty,general_stock,weight,status,recommended_price,images,characteristics,attachments,vat_id,family,start_date,estimated_stock,reversible_vat_charging,min_sale_price,max_sale_price,offer_details,offer_properties,product_measurements,availability,stock,handling_time,barcode,ean,commission,validation_status,offer_validation_status,ownership,best_offer_sale_price,best_offer_recommended_price,number_of_offers
DASDSA,1,11,123,brand,,Name,"part number",12.31,RON,description,https://www.url.com,12,10,0,1,12.19,Array,Array,Array,1,Array,Array,10,,11,200,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,1,11,11,1
D3129DKQW,1,456,123,Bluedio,,name,"part number",123,EUR,description,https://url.com,24,1,0,1,12,Array,Array,Array,1,Array,Array,144,,11,200,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,1,77.31,83.19,1


As you can see, there is array instead of values, can someone tell me why?



I tried reset() function but I get only the value from the first column ( part_number_key )



foreach ($json as $line) 
if (empty($firstLineKeys))
$firstLineKeys = array_keys($line); print_r("aici3"); fputcsv($f,
$firstLineKeys); print_r("aici3"); $firstLineKeys = array_flip($firstLineKeys);
fputcsv($f,
array_merge($firstLineKeys,
$line)); $first = reset($line); print_r($first);



I want to extract all columns but to show only the first row value from every from every column, for example at "images" column I would like to extract just the first url and same for the rest of columns



And one more thing, what is the best method to ignore few columns?



Thanks in advance!










share|improve this question
























  • Because the images and characteristics, etc, are arrays. If you want to get the values, you'll have to pull that data out individually as well.

    – aynber
    Mar 7 at 15:42











  • How would the result look for multiple values in the inner array?

    – Nico Haase
    Mar 7 at 15:44











  • @Nico Haase The best way would be to extract the first value but I don't know how...

    – cristi alexandru
    Mar 7 at 15:47











  • Well, that would be $array[0] then or reset($array) - but wouldn't you lose a lot of data then?

    – Nico Haase
    Mar 7 at 15:49











  • @cristialexandru - $first = reset($array);

    – ArtisticPhoenix
    Mar 7 at 15:49













0












0








0








I'm trying to convert a JSON response to CSV file but I have a problem about arrays
Here is the conversion code to CSV



$jsonString = file_get_contents("feed.json");
$jsonDecoded = json_decode($jsonString, true);
$json = $jsonDecoded['results'];
jsonToCsv($json, "feed.csv");

function jsonToCsv ($json, $csvFilePath = false, $boolOutputFile = false)

// See if the string contains something
if (empty($json))
die("The JSON string is empty!");


// If passed a string, turn it into an array
if (is_array($json) === false)
$json = json_decode($json, true);


// If a path is included, open that file for handling. Otherwise, use a temp file (for echoing CSV string)
if ($csvFilePath !== false)
$f = fopen($csvFilePath,'w+');
if ($f === false)
die("Couldn't create the file to store the CSV, or the path is invalid. Make sure you're including the full path, INCLUDING the name of the output file (e.g. '../save/path/csvOutput.csv')");


else
$boolEchoCsv = true;
if ($boolOutputFile === true)
$boolEchoCsv = false;

$strTempFile = 'feed' . date("U") . ".csv";
$f = fopen($strTempFile,"w+");


$firstLineKeys = false;
foreach ($json as $line)
if (empty($firstLineKeys))
$firstLineKeys = array_keys($line);
fputcsv($f, $firstLineKeys);
$firstLineKeys = array_flip($firstLineKeys);


// Using array_merge is important to maintain the order of keys acording to the first element
fputcsv($f, array_merge($firstLineKeys, $line));

fclose($f);

// Take the file and put it to a string/file for output (if no save path was included in function arguments)
if ($boolOutputFile === true)
if ($csvFilePath !== false)
$file = $csvFilePath;

else
$file = $strTempFile;


// Output the file to the browser (for open/save)
if (file_exists($file))
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Length: ' . filesize($file));
readfile($file);


elseif ($boolEchoCsv === true)
if (($handle = fopen($strTempFile, "r")) !== FALSE)
while (($data = fgetcsv($handle)) !== FALSE)
echo implode(",",$data);
echo "<br />";

fclose($handle);



// Delete the temp file
unlink($strTempFile);


?>


And here is a example of feed.json content



 
"isError":false,
"messages":[

],
"results":[

"part_number_key":"DASDSA",
"buy_button_rank":1,
"category_id":11,
"id":123,
"brand":"brand",
"vendor_category_id":null,
"name":"Name",
"part_number":"part number",
"sale_price":12.31,
"currency":"RON",
"description":"description",
"url":"https://www.url.com",
"warranty":12,
"general_stock":10,
"weight":"0",
"status":1,
"recommended_price":12.19,
"images":[

"url":"https://url.com/images.jpg1",
"display_type":1
,

"url":"https://url.com/images.jpg2",
"display_type":0
,

"url":"https://url.com/images.jpg3",
"display_type":0

],
"characteristics":[

"id":8937,
"value":"value"
,

"id":8930,
"value":"value"
,

"id":8927,
"value":"value"
,

"id":8928,
"value":"value"
,

"id":5537,
"value":"value"
,

"id":8932,
"value":"value"
,

"id":8934,
"value":"value"
,

"id":8929,
"value":"value"
,

"id":7235,
"value":"value"
,

"id":6556,
"value":"value"
,

"id":5401,
"value":"value"

],
"attachments":[

],
"vat_id":1,
"family":
"id":1104,
"name":"NAME",
"family_type_id":244
,
"start_date":[

],
"estimated_stock":10,
"reversible_vat_charging":false,
"min_sale_price":11,
"max_sale_price":200,
"offer_details":
"id":2484194,
"warranty_type":null,
"supply_lead_time":14
,
"offer_properties":[

],
"product_measurements":[

],
"availability":[

"warehouse_id":1,
"id":3

],
"stock":[

"warehouse_id":1,
"value":10

],
"handling_time":[

"warehouse_id":1,
"value":0

],
"barcode":[

],
"ean":[

],
"commission":
"value":"20.0000",
"type":"percentage",
"id":"123",
"priority":"4",
"created":"2010-01-16 11:25:02"
,
"validation_status":[

"value":9,
"description":"Approved documentation",
"errors":null

],
"offer_validation_status":
"value":1,
"description":"Saleable",
"errors":null
,
"ownership":1,
"best_offer_sale_price":11,
"best_offer_recommended_price":11,
"number_of_offers":1
,

"part_number_key":"D3129DKQW",
"buy_button_rank":1,
"category_id":456,
"id":123,
"brand":"Bluedio",
"vendor_category_id":null,
"name":"name",
"part_number":"part number",
"sale_price":123,
"currency":"EUR",
"description":"description",
"url":"https://url.com",
"warranty":24,
"general_stock":1,
"weight":"0",
"status":1,
"recommended_price":12,
"images":[

"url":"https://url.com/images.jpg1",
"display_type":1
,

"url":"https://url.com/images.jpg2",
"display_type":0
,

"url":"https://url.com/images.jpg3",
"display_type":0

],
"characteristics":[

"id":7774,
"value":"val"
,

"id":7947,
"value":"val"
,

"id":8001,
"value":"val"
,

"id":8937,
"value":"val"
,

"id":8930,
"value":"val"
,

"id":8927,
"value":"val"
,

"id":8928,
"value":"val"
,

"id":5537,
"value":"val"
,

"id":8932,
"value":"val"
,

"id":8934,
"value":"val"
,

"id":8929,
"value":"val"
,

"id":7235,
"value":"val"
,

"id":6556,
"value":"val"
,

"id":5401,
"value":"val"

],
"attachments":[

],
"vat_id":1,
"family":
"id":123456,
"name":"Name",
"family_type_id":244
,
"start_date":[

],
"estimated_stock":144,
"reversible_vat_charging":false,
"min_sale_price":11,
"max_sale_price":200,
"offer_details":
"id":242414,
"warranty_type":null,
"supply_lead_time":14
,
"offer_properties":[

],
"product_measurements":[

],
"availability":[

"warehouse_id":1,
"id":3

],
"stock":[

"warehouse_id":1,
"value":9

],
"handling_time":[

"warehouse_id":1,
"value":0

],
"barcode":[

],
"ean":[

],
"commission":
"value":"20.0000",
"type":"percentage",
"id":"12492",
"priority":"4",
"created":"2010-01-16 11:25:02"
,
"validation_status":[

"value":9,
"description":"Approved documentation",
"errors":null

],
"offer_validation_status":
"value":1,
"description":"Saleable",
"errors":null
,
"ownership":1,
"best_offer_sale_price":77.31,
"best_offer_recommended_price":83.19,
"number_of_offers":1

]



Here is the output of the conversion



part_number_key,buy_button_rank,category_id,id,brand,vendor_category_id,name,part_number,sale_price,currency,description,url,warranty,general_stock,weight,status,recommended_price,images,characteristics,attachments,vat_id,family,start_date,estimated_stock,reversible_vat_charging,min_sale_price,max_sale_price,offer_details,offer_properties,product_measurements,availability,stock,handling_time,barcode,ean,commission,validation_status,offer_validation_status,ownership,best_offer_sale_price,best_offer_recommended_price,number_of_offers
DASDSA,1,11,123,brand,,Name,"part number",12.31,RON,description,https://www.url.com,12,10,0,1,12.19,Array,Array,Array,1,Array,Array,10,,11,200,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,1,11,11,1
D3129DKQW,1,456,123,Bluedio,,name,"part number",123,EUR,description,https://url.com,24,1,0,1,12,Array,Array,Array,1,Array,Array,144,,11,200,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,1,77.31,83.19,1


As you can see, there is array instead of values, can someone tell me why?



I tried reset() function but I get only the value from the first column ( part_number_key )



foreach ($json as $line) 
if (empty($firstLineKeys))
$firstLineKeys = array_keys($line); print_r("aici3"); fputcsv($f,
$firstLineKeys); print_r("aici3"); $firstLineKeys = array_flip($firstLineKeys);
fputcsv($f,
array_merge($firstLineKeys,
$line)); $first = reset($line); print_r($first);



I want to extract all columns but to show only the first row value from every from every column, for example at "images" column I would like to extract just the first url and same for the rest of columns



And one more thing, what is the best method to ignore few columns?



Thanks in advance!










share|improve this question
















I'm trying to convert a JSON response to CSV file but I have a problem about arrays
Here is the conversion code to CSV



$jsonString = file_get_contents("feed.json");
$jsonDecoded = json_decode($jsonString, true);
$json = $jsonDecoded['results'];
jsonToCsv($json, "feed.csv");

function jsonToCsv ($json, $csvFilePath = false, $boolOutputFile = false)

// See if the string contains something
if (empty($json))
die("The JSON string is empty!");


// If passed a string, turn it into an array
if (is_array($json) === false)
$json = json_decode($json, true);


// If a path is included, open that file for handling. Otherwise, use a temp file (for echoing CSV string)
if ($csvFilePath !== false)
$f = fopen($csvFilePath,'w+');
if ($f === false)
die("Couldn't create the file to store the CSV, or the path is invalid. Make sure you're including the full path, INCLUDING the name of the output file (e.g. '../save/path/csvOutput.csv')");


else
$boolEchoCsv = true;
if ($boolOutputFile === true)
$boolEchoCsv = false;

$strTempFile = 'feed' . date("U") . ".csv";
$f = fopen($strTempFile,"w+");


$firstLineKeys = false;
foreach ($json as $line)
if (empty($firstLineKeys))
$firstLineKeys = array_keys($line);
fputcsv($f, $firstLineKeys);
$firstLineKeys = array_flip($firstLineKeys);


// Using array_merge is important to maintain the order of keys acording to the first element
fputcsv($f, array_merge($firstLineKeys, $line));

fclose($f);

// Take the file and put it to a string/file for output (if no save path was included in function arguments)
if ($boolOutputFile === true)
if ($csvFilePath !== false)
$file = $csvFilePath;

else
$file = $strTempFile;


// Output the file to the browser (for open/save)
if (file_exists($file))
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Length: ' . filesize($file));
readfile($file);


elseif ($boolEchoCsv === true)
if (($handle = fopen($strTempFile, "r")) !== FALSE)
while (($data = fgetcsv($handle)) !== FALSE)
echo implode(",",$data);
echo "<br />";

fclose($handle);



// Delete the temp file
unlink($strTempFile);


?>


And here is a example of feed.json content



 
"isError":false,
"messages":[

],
"results":[

"part_number_key":"DASDSA",
"buy_button_rank":1,
"category_id":11,
"id":123,
"brand":"brand",
"vendor_category_id":null,
"name":"Name",
"part_number":"part number",
"sale_price":12.31,
"currency":"RON",
"description":"description",
"url":"https://www.url.com",
"warranty":12,
"general_stock":10,
"weight":"0",
"status":1,
"recommended_price":12.19,
"images":[

"url":"https://url.com/images.jpg1",
"display_type":1
,

"url":"https://url.com/images.jpg2",
"display_type":0
,

"url":"https://url.com/images.jpg3",
"display_type":0

],
"characteristics":[

"id":8937,
"value":"value"
,

"id":8930,
"value":"value"
,

"id":8927,
"value":"value"
,

"id":8928,
"value":"value"
,

"id":5537,
"value":"value"
,

"id":8932,
"value":"value"
,

"id":8934,
"value":"value"
,

"id":8929,
"value":"value"
,

"id":7235,
"value":"value"
,

"id":6556,
"value":"value"
,

"id":5401,
"value":"value"

],
"attachments":[

],
"vat_id":1,
"family":
"id":1104,
"name":"NAME",
"family_type_id":244
,
"start_date":[

],
"estimated_stock":10,
"reversible_vat_charging":false,
"min_sale_price":11,
"max_sale_price":200,
"offer_details":
"id":2484194,
"warranty_type":null,
"supply_lead_time":14
,
"offer_properties":[

],
"product_measurements":[

],
"availability":[

"warehouse_id":1,
"id":3

],
"stock":[

"warehouse_id":1,
"value":10

],
"handling_time":[

"warehouse_id":1,
"value":0

],
"barcode":[

],
"ean":[

],
"commission":
"value":"20.0000",
"type":"percentage",
"id":"123",
"priority":"4",
"created":"2010-01-16 11:25:02"
,
"validation_status":[

"value":9,
"description":"Approved documentation",
"errors":null

],
"offer_validation_status":
"value":1,
"description":"Saleable",
"errors":null
,
"ownership":1,
"best_offer_sale_price":11,
"best_offer_recommended_price":11,
"number_of_offers":1
,

"part_number_key":"D3129DKQW",
"buy_button_rank":1,
"category_id":456,
"id":123,
"brand":"Bluedio",
"vendor_category_id":null,
"name":"name",
"part_number":"part number",
"sale_price":123,
"currency":"EUR",
"description":"description",
"url":"https://url.com",
"warranty":24,
"general_stock":1,
"weight":"0",
"status":1,
"recommended_price":12,
"images":[

"url":"https://url.com/images.jpg1",
"display_type":1
,

"url":"https://url.com/images.jpg2",
"display_type":0
,

"url":"https://url.com/images.jpg3",
"display_type":0

],
"characteristics":[

"id":7774,
"value":"val"
,

"id":7947,
"value":"val"
,

"id":8001,
"value":"val"
,

"id":8937,
"value":"val"
,

"id":8930,
"value":"val"
,

"id":8927,
"value":"val"
,

"id":8928,
"value":"val"
,

"id":5537,
"value":"val"
,

"id":8932,
"value":"val"
,

"id":8934,
"value":"val"
,

"id":8929,
"value":"val"
,

"id":7235,
"value":"val"
,

"id":6556,
"value":"val"
,

"id":5401,
"value":"val"

],
"attachments":[

],
"vat_id":1,
"family":
"id":123456,
"name":"Name",
"family_type_id":244
,
"start_date":[

],
"estimated_stock":144,
"reversible_vat_charging":false,
"min_sale_price":11,
"max_sale_price":200,
"offer_details":
"id":242414,
"warranty_type":null,
"supply_lead_time":14
,
"offer_properties":[

],
"product_measurements":[

],
"availability":[

"warehouse_id":1,
"id":3

],
"stock":[

"warehouse_id":1,
"value":9

],
"handling_time":[

"warehouse_id":1,
"value":0

],
"barcode":[

],
"ean":[

],
"commission":
"value":"20.0000",
"type":"percentage",
"id":"12492",
"priority":"4",
"created":"2010-01-16 11:25:02"
,
"validation_status":[

"value":9,
"description":"Approved documentation",
"errors":null

],
"offer_validation_status":
"value":1,
"description":"Saleable",
"errors":null
,
"ownership":1,
"best_offer_sale_price":77.31,
"best_offer_recommended_price":83.19,
"number_of_offers":1

]



Here is the output of the conversion



part_number_key,buy_button_rank,category_id,id,brand,vendor_category_id,name,part_number,sale_price,currency,description,url,warranty,general_stock,weight,status,recommended_price,images,characteristics,attachments,vat_id,family,start_date,estimated_stock,reversible_vat_charging,min_sale_price,max_sale_price,offer_details,offer_properties,product_measurements,availability,stock,handling_time,barcode,ean,commission,validation_status,offer_validation_status,ownership,best_offer_sale_price,best_offer_recommended_price,number_of_offers
DASDSA,1,11,123,brand,,Name,"part number",12.31,RON,description,https://www.url.com,12,10,0,1,12.19,Array,Array,Array,1,Array,Array,10,,11,200,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,1,11,11,1
D3129DKQW,1,456,123,Bluedio,,name,"part number",123,EUR,description,https://url.com,24,1,0,1,12,Array,Array,Array,1,Array,Array,144,,11,200,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,Array,1,77.31,83.19,1


As you can see, there is array instead of values, can someone tell me why?



I tried reset() function but I get only the value from the first column ( part_number_key )



foreach ($json as $line) 
if (empty($firstLineKeys))
$firstLineKeys = array_keys($line); print_r("aici3"); fputcsv($f,
$firstLineKeys); print_r("aici3"); $firstLineKeys = array_flip($firstLineKeys);
fputcsv($f,
array_merge($firstLineKeys,
$line)); $first = reset($line); print_r($first);



I want to extract all columns but to show only the first row value from every from every column, for example at "images" column I would like to extract just the first url and same for the rest of columns



And one more thing, what is the best method to ignore few columns?



Thanks in advance!







php arrays json csv






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 9:35







cristi alexandru

















asked Mar 7 at 15:40









cristi alexandrucristi alexandru

84




84












  • Because the images and characteristics, etc, are arrays. If you want to get the values, you'll have to pull that data out individually as well.

    – aynber
    Mar 7 at 15:42











  • How would the result look for multiple values in the inner array?

    – Nico Haase
    Mar 7 at 15:44











  • @Nico Haase The best way would be to extract the first value but I don't know how...

    – cristi alexandru
    Mar 7 at 15:47











  • Well, that would be $array[0] then or reset($array) - but wouldn't you lose a lot of data then?

    – Nico Haase
    Mar 7 at 15:49











  • @cristialexandru - $first = reset($array);

    – ArtisticPhoenix
    Mar 7 at 15:49

















  • Because the images and characteristics, etc, are arrays. If you want to get the values, you'll have to pull that data out individually as well.

    – aynber
    Mar 7 at 15:42











  • How would the result look for multiple values in the inner array?

    – Nico Haase
    Mar 7 at 15:44











  • @Nico Haase The best way would be to extract the first value but I don't know how...

    – cristi alexandru
    Mar 7 at 15:47











  • Well, that would be $array[0] then or reset($array) - but wouldn't you lose a lot of data then?

    – Nico Haase
    Mar 7 at 15:49











  • @cristialexandru - $first = reset($array);

    – ArtisticPhoenix
    Mar 7 at 15:49
















Because the images and characteristics, etc, are arrays. If you want to get the values, you'll have to pull that data out individually as well.

– aynber
Mar 7 at 15:42





Because the images and characteristics, etc, are arrays. If you want to get the values, you'll have to pull that data out individually as well.

– aynber
Mar 7 at 15:42













How would the result look for multiple values in the inner array?

– Nico Haase
Mar 7 at 15:44





How would the result look for multiple values in the inner array?

– Nico Haase
Mar 7 at 15:44













@Nico Haase The best way would be to extract the first value but I don't know how...

– cristi alexandru
Mar 7 at 15:47





@Nico Haase The best way would be to extract the first value but I don't know how...

– cristi alexandru
Mar 7 at 15:47













Well, that would be $array[0] then or reset($array) - but wouldn't you lose a lot of data then?

– Nico Haase
Mar 7 at 15:49





Well, that would be $array[0] then or reset($array) - but wouldn't you lose a lot of data then?

– Nico Haase
Mar 7 at 15:49













@cristialexandru - $first = reset($array);

– ArtisticPhoenix
Mar 7 at 15:49





@cristialexandru - $first = reset($array);

– ArtisticPhoenix
Mar 7 at 15:49












0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55047628%2fjson-array-convert-to-csv%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55047628%2fjson-array-convert-to-csv%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived