Right appraoch to use to Create csv out of php array - php

When i var_dump the contents of my array, i get the following results. I would like to be able to put the following contents into a csv file. For simplicity reasons, i have not displayed all the values of the array
Array
(
[0] => Array
(
[0] => NEWS 1
[1] => 00
[2] => 0
)
[1] => Array
(
[0] => NEWS 1
[1] => 01
[2] => 0
)
[2] => Array
(
[0] => NEWS 1
[1] => 02
[2] => 0
)
[3] => Array
(
[0] => NEWS 1
[1] => 03
[2] => 0
)
[4] => Array
(
[0] => NEWS 1
[1] => 04
[2] => 0
)
)
I would like to be able to insert the contents of that array into a csv file. My final csv file should like this
NEWS 1,0,0,0,0,0
I have tried several methods without sucess. So useless to post my code here. I would like to start from scratch. If some one can advise me on the right apparoach to use or propose me some code, it will be very great

I can give you this code I wrote long time ago.. it creates a csv line from an array... maybe it can inspire you. It is in a class called CSVWriter.
private static function writeFile($handle, $data, $pos) {
if(count($data) == 0) {
return false;
} else {
$element = $pos === 0 || $pos === count($data) - 1 ? $data[$pos] : ';'.$data[$pos];
$fwrite = fwrite($handle, $element);
if($fwrite === false || ($pos + 1 === count($data))) {
return $fwrite;
} else {
CSVWriter::writeFile($handle, $data, ++$pos);
}
}
}

Related

Replace values in associative array

I'm consuming an API which returns an array of objects as this:
$base = array(
["orange","_","banana"],
["banana","_","_"],
["_","apple","kiwi"],
["_","raspberry","strawberry"]
);
And I intend to show "0" when key value is "_" however I haven't found a better way to do this than this:
foreach ($base as $key => $value) {
for ($i=0; $i<=3;$i++) {
if ($base[$key][$i]=="_")
$base[$key][$i]="0";
}
}
This works just fine since it's a simple demo but the real array is sometimes big and I've found this solution somewhat inefficient.
My question is, there's some php built-in function to do achieve this in or at least a better way to do this?
Thanks in advance guys,
Use array_walk_recursive(), pass the elements by reference and walk over the array, checking for the value _ - if its a match, replace it with 0.
$base = array(
["orange","_","banana"],
["banana","_","_"],
["_","apple","kiwi"],
["_","raspberry","strawberry"]
);
array_walk_recursive($base, function(&$v) {
if ($v === '_')
$v = 0;
});
Output becomes
Array
(
[0] => Array
(
[0] => orange
[1] => 0
[2] => banana
)
[1] => Array
(
[0] => banana
[1] => 0
[2] => 0
)
[2] => Array
(
[0] => 0
[1] => apple
[2] => kiwi
)
[3] => Array
(
[0] => 0
[1] => raspberry
[2] => strawberry
)
)
Live demo at https://3v4l.org/6Bs8ZE
You can replace _ with 0;
json_decode(str_replace('"_"','"0"',json_encode($base)));

How to get a user log failed details in log file

In a log file I want get a how many times user is log failed and the date details I have code for this but its not working correctly.
This is a code
$file = new SplFileObject("failed.log", "r");
while(!$file->eof())
{
$data[] = current (($file->fgetcsv("|"))) . next (($file->fgetcsv("|")));
}
$abc = implode(",", $data);
echo $abc;
$br = "\n";
In this code I am getting like this
John26:Dec:2017:16:15:27,Abc29:Dec:2017:09:39:45,Bhumi29/Dec/2017 14:15:41,Abc
Its not correct, it read first line name and and second line date I don't no what is wrong in my code.
This is my log failed details
John|26:Dec:2017:16:09:45|192.168.0.101|CentaurOne|Failed
cena|26:Dec:2017:16:15:27|192.168.0.101|CentaurOne|Failed
Abc|27:Dec:2017:09:25:25|192.168.0.101|CentaurOne|Failed
Bhumi|29:Dec:2017:09:39:45|192.168.0.101|CentaurOne|Failed
Bhumi|29:Dec:2017:10:19:28|192.168.0.101|CentaurOne|Failed
Avccc|29/Dec/2017 14:15:41|192.168.0.101|CentaurOne|Failed
Abc|04/Jan/2018 15:54:35|192.168.0.101|CentaurOne|Failed
As suggested in the comments, you should rethink saving failed logins to a text log especially if you intend to make this a routine action. As the file grows, it will become memory intensive:
# Saves contents of file into array by end of lines
$explode = file("failed.log",FILE_SKIP_EMPTY_LINES);
# Loop rows
foreach($explode as $row) {
# Explode the | character
$exp = explode('|',$row);
# Save the user to the an array
$new[$exp[0]]['dates'][] = $exp[1];
# Count how many times tried
if(!isset($new[$exp[0]]['count']))
$new[$exp[0]]['count'] = 1;
else
$new[$exp[0]]['count'] += 1;
}
print_r($new);
Should give you:
Array
(
[John] => Array
(
[dates] => Array
(
[0] => 26:Dec:2017:16:09:45
)
[count] => 1
)
[cena] => Array
(
[dates] => Array
(
[0] => 26:Dec:2017:16:15:27
)
[count] => 1
)
[Abc] => Array
(
[dates] => Array
(
[0] => 27:Dec:2017:09:25:25
[1] => 04/Jan/2018 15:54:35
)
[count] => 2
)
[Bhumi] => Array
(
[dates] => Array
(
[0] => 29:Dec:2017:09:39:45
[1] => 29:Dec:2017:10:19:28
)
[count] => 2
)
[Avccc] => Array
(
[dates] => Array
(
[0] => 29/Dec/2017 14:15:41
)
[count] => 1
)
)
Use print_r() to see how to access array key/values.

Creating directories based on array values

I get a response from an API call that looks like the following
Array
(
[_id] => aasdasdasdasdasd
[created] => 2017-01-16T14:11:54.616Z
[options] => Array
(
[title] => 1
[data] => Array
(
[0] => Array
(
[labelName] => Date
[labelValues] => Array
(
[0] => March 2016
)
)
[1] => Array
(
[labelName] => Title
[labelValues] => Array
(
[0] => Food
)
)
[2] => Array
(
[labelName] => Product
[labelValues] => Array
(
[0] => Rice
)
)
)
)
)
I then process the response by doing the following
$results = array();
foreach ($output['options']['data'] as $data) {
if (isset($data['labelValues'][0])) {
$results[$data['labelName']] = $data['labelValues'][0];
}
}
This leaves me with something along the lines of this
Array
(
[Date] => March 2016
[Title] => Food
[Product] => Rice
)
Putting it into an array was not my intention, it was mainly done to help me better understand the looping required to process the original data.
My main intention is to create directories from these values. The main directory will be the Date, within this should be the Title and within this should be Product. So for the above, the directory structure should be something like 2016 > Food > Rice.
In order to achieve this, I have come up with the following
foreach ($output['options']['data'] as $data) {
if (isset($data['labelValues'][0])) {
if($data['labelName'] == 'Date') {
if (preg_match('/\b\d{4}\b/', $data['labelValues'][0], $matches)) {
$results[$data['labelName']] = $matches[0];
if (!file_exists($matches[0])) {
mkdir($matches[0], 0777, true);
}
}
}
}
}
The above works well and creates the date folder for me. Where I am struggling is how I now create the Title folder within the Date folder, and then the Product within the Title.
How would I go about achieving this?
Many thanks
I like your created array:
$array = array
(
[Date] => March 2016
[Title] => Food
[Product] => Rice
)
Simply implode the path:
mkdir(implode('/', $array), 0777, true);
This will create all of the directories, March 2016/Food/Rice

Array Data show not work

After querying my data from database I have this type of array in $rown
Array
(
[0] => 60
[id] => 60
[1] => 78
[cholest] => 78
[2] => 2014-07-13
[Cdate] => 2014-07-13
)
Array
(
[0] => 61
[id] => 61
[1] => 0
[cholest] => 0
[2] => 2014-07-15
[Cdate] => 2014-07-15
)
My code
$resultn = mysql_query($sqln);
if(mysql_affected_rows() > 0)
{
while($rown = mysql_fetch_array($resultn))
{
$result_finalb = $rown["id"];
}
}
when I print $result_finalb then show only second array data, but I want to show both array data.
You are setting a single variable $result_finalb with a value.
If you want to create an array of values, using $result_finalb[] will create an array item with the value you assign.
The first time will be $result_finalb[0], second will be $result_finalb[1], and so on through however many iterations you go through.
You are missing square brackets. Use this:
$resultn = mysql_query($sqln);
if(mysql_affected_rows() > 0)
{
while($rown = mysql_fetch_array($resultn))
{
$result_finalb[] = $rown["id"];
}
}

Regex to Extract Report ID Out of a multi-dimensional array with PHP

Here's my problem. We got some sample PHP that didn't work so I've been trying to write this more or less "by the seat of my pants". My regex is rusty and I've not dealt with multidimensional arrays, so this is outside my realm of experience.
I'm getting an array like this one but I only want the report ID's where [1] contains the word "Export" and then I need to pass those to another script where I have to do more or less the same thing to get a result set ID that I can pass to another script that I can actually export.
[0] => Array
(
[0] => REPORTIDXXXXXXXXXXXXXXXXXXXXXXXXXXX
[1] => REPORT EXPORT NAME#1
[2] => REPORT DESCRIPTION #1
[3] => 2012-10-02T17:31:30
)
[1] => Array
(
[0] => REPORTIDYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
[1] => REPORTOTHERNAME#2
[2] => REPORTDESCRIPTION #2
[3] => 2012-09-28T15:15:17
)
[2] => Array
(
[0] => REPORTIDZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
[1] => REPORT EXPORT NAME#3
[2] => REPORT DESCRIPTION #3
[3] => 2012-09-28T14:59:17
)
Something like this should work:
function get_report_ids(array $rs) {
$results = array();
// loop over your data structure
foreach($rs as $key => $data) {
// If element 1 contains EXPORT (case insensitive)
if(stripos($data[1], 'EXPORT') !== false) {
// regex to capture the ID from element 0
if(preg_match('/^EXPORTID(.*)$/i', $data[0], $matches)) {
// add the ID to the results array
$results[] = $matches[1];
}
}
}
// if we had results then return the array, otherwise return null
return !empty($results) ? $results : null;
}
Example return value:
array(
0 => 'XXXXXXXXXXXXXXXXXXXXXXXXXXX',
1 => 'ZZZZZZZZZZZZZZZZZZZZZZZZZZZZ'
)

Categories