Bulk insert/export an array into a CSV file using PHP - php

I want to export an associative array into a .csv file. I'm using fputcsv() inside a foreach loop to insert the rows one at a time.
Here's my code:
$headers = array("Parent ID", "Company Name", "Created By", "Created Time", "Mandatory", "Valid", "Total Count", "Audit");
foreach ($cursorCount as $eachCursorCount) {
foreach ($cursor as $eachCursor) {
if ($eachCursorCount["createdBy"] == $eachCursor["createdby"]) {
$insertVal = array(
"parentid" => $eachCursor['parentid'],
"companyName" => $eachCursor['companyname'],
"createdby" => $eachCursor['createdby'],
"createdtime" => date('Y-m-d H:i:s', $eachCursor['createdtime']->sec),
"mandatory" => $eachCursor['mandatory'],
"valid" => $eachCursor['valid'],
"totalCount" => $eachCursorCount['totalCount'],
"audit" => $eachCursorCount['audit']
);
array_push($res_arr_values, array_values($insertVal));
}
}
}
}
$fp1 = fopen('export.csv', 'w');
fputcsv($fp1, $headers);
foreach ($res_arr_values as $fields)
{
fputcsv($fp1, $fields);
}
fclose($fp1);
Is there any method using which one can insert multiple rows at a time? (Or any other method with much lesser time complexity.)
Thank You.

Related

Convert threeDimensionalArray to Two and save csv

I have problem with convert array. I have structure like as
$threeDimensionalArray = [
[
[
'name' => 'name1',
],
[
'name' => 'name2',
],
],
[
[
'time' => 123,
'anyField'=>22222,
'anyField1'=>22222,
'anyField2'=>22222
],
[
'time' => 457,
'anyField'=>22222,
'anyField1'=>22222,
'anyField2'=>22222
],
],
];
I need convert this array to two dimensional and save each array to csv file via fputscsv
example
first line in CSV
'name1','name2',
second line
123, 457, etc
This solution will help in your specific case:
$to_csv = [];
foreach ($threeDimensionalArray as $first_level) {
foreach ($first_level as $second_level) {
foreach ($second_level as $key => $value) {
$to_csv[$key][] = $value;
}
}
}
$fp = fopen('file.csv', 'w');
foreach ($to_csv as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
The idea is to firstly configure array to two layers array with grouping by key and use fputcsv() afterwards.
I resolve this problem :)
foreach ($threeDimensionalArray as $firstDimensional) {
$array= [];
foreach ($firstDimensional as $twoDimensional) {
$array[] = $twoDimensional['name'] ?? null .$twoDimensional['time'] ?? null;
}
fputcsv($fp, $array);
$returnArray[]=$array;
}

Adding multiple image urls to JSON object

What i am trying to do is make my JSON object the same as an already developed one, these are the displays:
Original:
{
"name": "test product",
"descriptionUrl": "https:\/\/www.site.club\/",
"images": [
"https:\/\/thesite.com\/kf\/HTB1bGBljyAKL1JjSZFoq6ygCFXa7\/TY-Unicorn-Big-Eyes-Plush-Toys-Ty-Beanie-Boos-Kids-Lovely-Children-Gifts-Kawaii-Stuffed-Animals.jpg",
"https:\/\/thesite.com\/kf\/HTB1rCK3bfJNTKJjSspoq6A6mpXaJ\/TY-Unicorn-Big-Eyes-Plush-Toys-Ty-Beanie-Boos-Kids-Lovely-Children-Gifts-Kawaii-Stuffed-Animals.jpg",
"https:\/\/thesite.com\/kf\/HTB1zWO2eGmWQ1JjSZPhq6xCJFXaa\/TY-Unicorn-Big-Eyes-Plush-Toys-Ty-Beanie-Boos-Kids-Lovely-Children-Gifts-Kawaii-Stuffed-Animals.jpg",
"https:\/\/thesite.com\/kf\/HTB13sOWXoRIWKJjSZFgq6zoxXXah\/TY-Unicorn-Big-Eyes-Plush-Toys-Ty-Beanie-Boos-Kids-Lovely-Children-Gifts-Kawaii-Stuffed-Animals.jpg"
],
"priceRange": {
"minPrice": "19.99",
"maxPrice": "19.99",
"currency": "USD"
},
"descriptionHtml": "HTML code can potentially go here!",
"descriptionText": "Test product description"
}
My Attempt:
{
"name": "test product",
"descriptionUrl": "https:\/\/www.site.club\/",
"images": "https:\/\/www.site.club\/images\/img-instagram-icon.png",
"priceRange": {
"minPrice": "19.99",
"maxPrice": "19.99",
"currency": "USD"
},
"descriptionHtml": "HTML code can potentially go here!",
"descriptionText": "Test product description"
}
The code i have written so far is:
<?php
if (isset($_POST['submitNewProduct'])) {
// TRY/CATCH //
try {
// 1 - PRICE ARRAY //
$prices = [];
foreach (['minPrice', 'maxPrice'] as $searchField) {
$prices[$searchField] = $_POST['product_price'];
}
$prices['currency'] = 'USD';
// 2 - IMAGES ARRAY //
$images = [];
$images = "https://www.site.club/images/img-header-39847.png";
$images = "https://www.site.club/images/img-instagram-icon.png";
// SETUP THE JSON OBJECT //
$productData = array('name' => $_POST['product_name'],
'descriptionUrl' => getUrl(),
'images' => $images,
'priceRange' => $prices,
'descriptionHtml' => 'HTML code can potentially go here!',
'descriptionText' => $_POST['product_description']
);
print_r($productData);
// INSERTION //
$i = DB::getInstance()->insert(
'products',
[
'product_unique_id' => generateId("wlu", $member),
'product_category_id' => 0,
'product_name' => $_POST['product_name'],
'product_json_body' => json_encode($productData, JSON_PRETTY_PRINT),
'product_url' => getUrl(),
'product_active' => 'Y',
'product_date' => date('Y-m-d H:i:s')
]);
stdmsg("...");
} catch (Exception $e) {
stderr($e->getMessage());
}
}
?>
The issue is when i'm adding images, in the original JSON object, it is displayed between the [ ] square brackets, also in my test above i cannot add multiple images to the JSON object like the original format, any help would be appreciated.
In this line
$images = "https:... ";
you are overwriting the array $images you've defined just before.
You want to add, so you've got the choice of doing
$images[] = "https:....";
or
array_push($images, "https://www...");
or already add the strings when creating the array:
// images = []; // not needed then!
$images = ["https:..firstimage..", "https:secondimage"];
After declaring image array, accidently you are over writing it you should assigen image names on different different indexes like
$images[0] = "string image name" and so on..
or use array_push method to push entries in images variavle which is an array.
Hope it will work.

Multidimensional Array for() with different numbered elements levels

How would I write a foreach loop that would print off all information with the following multidimensional array without using any functions:
$workers = array(
"Natalie" => array
("First term" => array(
"Subworker" => "Susan",
"Length" => '1900-2000',
"Notes" => "Finished all tasks"),
"Second term" => array(
"Subworker" => "Laura",
"Length" => '1985-1986'),
),
"Laura" => array(
"First term" => array(
"Subworker" => "Sarah",
"Length" => '1999-1992'),
),
"Carolyn" => array(
"First term" => array(
"Subworker" => "Jenny",
"Length" => '1900 -1945',
"Notes" => array
("Finished all tasks",
"Did not finish all tasks",
"Completed partial tasks" )
),
),
"Jacob" => array(
"First term" => array(
"Subworker" => "Danielle",
"Length" => '1993-1994',
"Notes" => "Finished all tasks"),
),
"Jenny" => array(
"First term" => array(
"Subworker" => "Angela",
"Length" => '1999 - 2001'),
"Second term" => array(
"Subworker" => array(
"Paula" => "Let Go",
"Steve" => "Hired"),
"Length" => '1987 - 1999',
"Notes" => "Hired"),
)
);
/****So far I've done the following, but it is not printing out everything. For example, it is not printing out under Jenny, Second term, Subworker Paula and Steve./*****
foreach($workers as $worker => $value) {
foreach ($value as $newkey => $info) {
echo $worker.':<br>'.$newkey.':<br>';
foreach ($value as $newkey) {
echo 'Subworker: '.$newkey["Subkey"].'<BR>';
foreach ($value as $newkey) {
echo 'Length: '.$newkey["Length"].'<BR>';
foreach ($value as $newkey) {
echo 'Notes: '.$newkey["Notes"].'<BR>';
}
}
}
}
}
It is necessary to cross by a function and to make small tests upstream, it is always useful to avoid the return of error in environment of dev. :)
I have to add lists (ul, li) for better one reading
if (is_array($workers) && !empty($workers)) {
echo loopArray($workers);
} else {
echo "<ul><li>".$workers."</li></ul>";
}
function loopArray($array)
{
$result = "";
$result .= "<ul>";
foreach ($array as $item => $value) {
if (is_array($value) && !empty($value)) {
$result .= "<li>".$item;
$result .= loopArray($value)."</li>";
} else {
$result .= "<ul><li>".$item.': '.$value."</li></ul>";
}
}
$result .= "</ul>";
return $result;
}
To print the particular array you've provided, without using functions:
// workers
foreach($workers as $worker => $workerarr) {
echo $worker.":<ul>\n";
// worker terms
foreach ($workerarr as $term => $terminfo) {
echo "<li>$term:<ul>\n";
// term info
foreach ($terminfo as $type => $typevalue) {
echo "<li>$type: ";
// is type value an array?
if ( is_array($typevalue) ) {
// if so, put in list
echo "<ul>\n";
foreach ($typevalue as $label => $value) {
$label = is_int($label)? '': "$label: "; // only print text
echo "<li>$label$value</li>\n";
}
echo "</ul>";
}
// if not...
else {
echo $typevalue;
}
echo "</li>\n";
}
echo "</ul></li>\n";
}
echo "</ul>";
}
Using unordered lists to help display the information in a readable manner. To see with only break tags as in the question, see PHP Sandbox - Original
PHP Sandbox - Unordered Lists

convert php response array as comma separated [duplicate]

This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
I am trying to get facebook friends by using facebook api.
I am getting response
{
"data": [
{
"id": "groupID",
"members": {
"data": [
{
"name": "Abc",
"administrator": false,
"id": "xxxxxx"
},
{
"name": "NewCas",
"administrator": false,
"id": "xxxxxxxxx"
},
{
"name": "Cds",
"administrator": false,
"id": "xxxxxxxxx"
},
{
"name": "akaha",
"administrator": false,
"id": "xxxxxxx"
},
}
}
This is my code
$fql = 'https://graph.facebook.com/me/groups?fields=id,members&access_token='.$access_token.'&limit=3';
$fqlresult = file_get_contents($fql);
$f = json_decode($fqlresult, true);
tried implode.
$result = implode(',', array_column($f['data'], 'id'));
I am getting this response
GroupID,GroupID,GroupID
I want to take response user ids (members id) as
xxxxxx,xxxxxx,xxxxxx,xxxxxx,xxxxxx,xxxxxx,xxxxxx
Thanks
The other answers are almost correct, but the data is an array with one element so it should be:
echo implode(',', array_column($f['data'][0]['members']['data'], 'id'));
and that is when you have only one groupid, if you have multiple group ids you will need to loop trough it. (loop over the [0] by checking $groupcount = count($f['data']);
This works...
$arr = array(
'data' => array(
array('id' => 'xxxx1'),
array('id' => 'xxxx2'),
array('id' => 'xxxx3'),
array('id' => 'xxxx4'),
array('id' => 'xxxx5'),
array('id' => 'xxxx6'),
array('id' => 'xxxx7'),
array('id' => 'xxxx8'),
)
);
echo implode(',', array_column($arr['data'], 'id'));
EDIT - based on your update and change of request...
echo implode(',', array_column($arr['data'][0]['members']['data'], 'id'));
please review http://php.net/manual/en/language.types.array.php and the section on multidimensional arrays
$data_arr=json_decode($data,true);
$return_str="";
foreach($data_arr['data'] as $row)
{
$return_str .=implode(", ", array_column($row['members']['data'], 'id')) ;
}
echo rtrim($return_str,",");
This will work for multiple elements in $f['data'].
echo implode(',', array_column($f['data'][0]['members']['data'], 'id'));
Make sure your PHP version is 5.5+. Below the specified version will not support array_column function. You can also use this code without array_column.
$data = $result['data'][0]['members']['data'];
$keyValue = '';
foreach ($data as $outerKey => $outerValue) {
foreach ($outerValue as $key => $value) {
if($key == 'id'){
$keyValue .= $value . ' ';
}
}
}
echo $keyValue;

PHP push array into existing array

I have a php file I am using to create a JSON output. You can see my loop in the code below:
foreach($objQueueData->event as $event){
$output[] = array(
"eventID" => (int)$event->trainingEventID,
"eventTitle" => (string)$event->teTitle,
"eventDescription" => (string)$event->teDesc,
"eventSource" => (string)$event->teSource,
"eventType" => (string)$event->teType,
"eventMedium" => (string)$event->teMedium,
"eventRequestor" => (string)$event->creatorFirst . ' ' . $event->creatorLast,
"eventRequestorNTID" => (string)$event->creatorNTID,
"eventRequestDate" => (string)$event->teCreated,
"eventDirector" => (string)$event->teDirector,
"eventTeammateImpact" => (string)$event->teTeammateImpact,
"eventCustomerImpact" => (string)$event->teCustomerImpact,
"eventComplexity" => (string)$event->teComplexity,
"eventInitiativeID" => (int)$event->intID,
"eventNeededBy" => (string)$event->teNeededBy
);
$impactedRegions = array();
if(isset($event->regionalImpact->option)){
foreach ($event->regionalImpact->option as $region) {
$impactedRegions[] = $region->impact;
}
array_push($output, $impactedRegions);
}
}
// Set the content type to JSON for jquery to understand
header('Content-Type: text/json');
// Print the response to the page
print json_encode($output);
My issue is with the second array impactedRegions. This should be a sub array of output but it is not working as intended.
I am trying to have it be apart of the output array.
Here is what the current JSON output looks like:
[
{
"eventID": 25,
"eventTitle": "Monday",
"eventDescription": "Testing Monday",
"eventSource": "OE",
"eventType": "New Hire",
"eventMedium": "ILT",
"eventRequestor": "Carl",
"eventRequestorNTID": "ch123",
"eventRequestDate": "Nov 17 2014 4:58PM",
"eventDirector": "",
"eventTeammateImpact": "Medium",
"eventCustomerImpact": "High",
"eventComplexity": "Low",
"eventInitiativeID": 1069,
"eventNeededBy": "2014-11-18"
},
[
{
"0": "Americas"
}
],
Can anyone point me in the right direction?
foreach ($event->regionalImpact->option as $region) {
$output['regions'][] = $region->impact;
}
Try this
foreach($objQueueData->event as $key => $event){
$output[$key] = array(
"eventID" => (int)$event->trainingEventID,
"eventTitle" => (string)$event->teTitle,
"eventDescription" => (string)$event->teDesc,
"eventSource" => (string)$event->teSource,
"eventType" => (string)$event->teType,
"eventMedium" => (string)$event->teMedium,
"eventRequestor" => (string)$event->creatorFirst . ' ' . $event->creatorLast,
"eventRequestorNTID" => (string)$event->creatorNTID,
"eventRequestDate" => (string)$event->teCreated,
"eventDirector" => (string)$event->teDirector,
"eventTeammateImpact" => (string)$event->teTeammateImpact,
"eventCustomerImpact" => (string)$event->teCustomerImpact,
"eventComplexity" => (string)$event->teComplexity,
"eventInitiativeID" => (int)$event->intID,
"eventNeededBy" => (string)$event->teNeededBy
);
$impactedRegions = array();
if(isset($event->regionalImpact->option)){
foreach ($event->regionalImpact->option as $region) {
$impactedRegions[] = $region->impact;
}
}
$output[$key]['impactedRegions'] = $impactedRegions;
}
// Set the content type to JSON for jquery to understand
header('Content-Type: text/json');
// Print the response to the page
print json_encode($output);
I think the problem you are having is you are using array_push() with an associative array. I believe array_push is for pushing values to an indexed array.
Trying specifying the key by using $output['impactedRegions'] = $impactedRegions; instead.
$impactedRegions = array();
if(isset($event->regionalImpact->option)){
foreach ($event->regionalImpact->option as $region) {
$impactedRegions[] = $region->impact;
}
$output['impactedRegions'] = json_encode($impactedRegions);
}
Also, json_encode($impactedRegions) will encode the array so it's included as a json object in your original array.

Categories