Преобразование массива JSON в CSV

#php #arrays #json #csv

#php #массивы #json #csv

Вопрос:

Я пытаюсь преобразовать ответ JSON в файл CSV, но у меня проблема с массивами, вот код преобразования в 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);

  }
?>
  

А вот пример feed.содержимое json

  {
   "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
      }
   ]
}
  

Вот результат преобразования

 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
  

Как вы можете видеть, вместо значений используется массив, кто-нибудь может сказать мне, почему?

Я попробовал функцию reset(), но я получаю только значение из первого столбца ( 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);
}
  

Я хочу извлечь все столбцы, но для отображения только значения первой строки из каждого столбца, например, в столбце «изображения» я хотел бы извлечь только первый URL-адрес и то же самое для остальных столбцов

И еще одна вещь, каков наилучший способ игнорировать несколько столбцов?

Заранее спасибо!

Комментарии:

1. Потому что изображения, характеристики и т.д. Являются массивами. Если вы хотите получить значения, вам также придется извлекать эти данные по отдельности.

2. Как результат будет выглядеть для нескольких значений во внутреннем массиве?

3. @Nico Haase Лучшим способом было бы извлечь первое значение, но я не знаю как…

4. Ну, это было бы $array[0] тогда или reset($array) — но разве вы не потеряли бы тогда много данных?

5. @cristialexandru — $first = reset($array);