Splitting date and time then put into other column [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm working a small date time project. From my CSV file I have 4 columns, called Name, Employee ID, Data/Time, Status and in my Database columns are name, empID, date, timeIn, timeOut, Status.
Picture of my csv file: (Picture A)
And here is what I want to save in my database: (Picture B)
Example input CSV string:
Name,"Empoyee ID",Date/Time,Status
"Soriano, Jhoniel",901,"05/03/2019 1:01:03 PM",C/Out
"Soriano, Jhoniel",901,"05/04/2019 2:01:03 PM",C/In
"Soriano, Jhoniel",901,"05/04/2019 3:01:03 PM",C/Out
"Soriano, Jhoniel",901,"05/06/2019 4:01:03 PM",C/In
"Soriano, Jhoniel",901,"05/06/2019 5:01:03 PM",C/Out
"Soriano, Jhoniel",901,"05/07/2019 6:01:03 PM",C/In
How can I get started on this problem?
Edit
I want to thanks #jimmix for giving me some idea to get started.
Here is the real scenario:
From my CSV file, I have the data you can found at (Picture A), then I will upload using my upload() function in into my MySQL database with the table name "tbldumpbio",
See the table structure below:
From my table tbldumpbio data, I have a function called processTimesheet()
Here's the code:
public function processTimesheet(){
$this->load->model('dbquery');
$query = $this->db->query("SELECT * FROM tbldumpbio");
foreach ($query->result() as $row){
$dateTimeExplArr = explode(' ', $row->datetimex);
$dateStr = $dateTimeExplArr[0];
$timeStr = $dateTimeExplArr[1];
if($row->status='C/Out' and !isset($timeStr) || empty($timeStr) ){
$timeStrOut ='';
} else {
$timeStrOut = $dateTimeExplArr[1];
}
if($row->status='C/In' and !isset($timeStr) || empty($timeStr) ){
$timeStrIn ='';
} else {
$timeStrIn = $dateTimeExplArr[1];
}
$data = array(
'ID' => '',
'companyAccessID' => '',
'name' => $row->name,
'empCompID' => $row->empid,
'date' => $dateStr,
'timeIn' => $timeStrIn,
'timeOut' => $timeStrOut,
'status' => '',
'inputType' => ''
);
$this->dbquery->modInsertval('tblempbioupload',$data);
}
}
This function will add a another data into tblempbioupload. But here are the results that I'm getting with:
Please see the below data:
The problem is:
the date should not be duplicated
Time In data should be added if the status is 'C/In'
Time Out data should be added if the status is 'C/Out'
The expected result should be something like this:

Not the shortest one but working:
<?php
$csvMultilineStr =
'Name,"Empoyee ID",Date/Time,Status
"Soriano, Jhoniel",901,"05/03/2019 1:01:03 PM",C/Out
"Soriano, Jhoniel",901,"05/04/2019 2:01:03 PM",C/In
"Soriano, Jhoniel",901,"05/04/2019 3:01:03 PM",C/Out
"Soriano, Jhoniel",901,"05/06/2019 4:01:03 PM",C/In
"Soriano, Jhoniel",901,"05/06/2019 5:01:03 PM",C/Out
"Soriano, Jhoniel",901,"05/07/2019 6:01:03 PM",C/In';
//read CSV as every line = 1 array item
$csvArr = explode("\n", $csvMultilineStr);
//get header line as array of column names
//and remove that line from $csvArr
$headerArr = str_getcsv(array_shift($csvArr));
$emplIdKeyStr = "Empoyee ID";
$resultArr = [];
/**
* Create array of arrays
* that each array inside an array
* is under key of emploeeId and
* represents one CSV row
*
* [
* 901 => [
* 0 => [
* 'Name' => value
* 'Empoyee ID' => value2
* ...
* ],
* 1 => [
* 'Name' => value
* 'Empoyee ID' => value2
* ...
* ]
* ]
* ]
*
*/
foreach($csvArr as $csvLineStr) {
$csvEntryArr = str_getcsv($csvLineStr);
$csvLineArr = array_combine($headerArr, $csvEntryArr);
$emplIdInt = $csvLineArr[$emplIdKeyStr];
$resultArr[$emplIdInt][] = $csvLineArr;
}
var_export($resultArr);
/**
* Create array of arrays
* as above but with key => value
* structure
*
* [
* 901 => [
* '05/03/2019' => [
* 'C/In' => ...
* 'C/Out' => ...
* 'name' => ...
* ]
* ]
* ]
*
*/
$resultTimeIoArr = [];
$timeInOutColSwStr = 'Status';
$dateTimeColStr = 'Date/Time';
foreach($resultArr as $emplIdInt => $emplEntyArr) {
foreach($emplEntyArr as $emplSingleEntryArr) {
$dateTimeStr = $emplSingleEntryArr[$dateTimeColStr];
$dateTimeExplArr = explode(' ', $dateTimeStr);
$dateStr = $dateTimeExplArr[0];
$timeStr = $dateTimeExplArr[1];
$resultTimeIoArr[$emplIdInt][$dateStr][$emplSingleEntryArr[$timeInOutColSwStr]] = $timeStr;
$resultTimeIoArr[$emplIdInt][$dateStr]['name'] = '"' . $emplSingleEntryArr['Name'] . '"';
}
}
/**
* get sorted array by EmplId, Date, C/In or C/Out
* as an arry similar to first one CsvArr
*/
$resultCsvArr = [];
$resultCsvLineArr = [];
foreach($resultTimeIoArr as $emplIdInt => $singleEmplArr) {
foreach($singleEmplArr as $dateStr => $signleIoArr) {
$resultCsvLineArr['Name'] = $signleIoArr['name'];
$resultCsvLineArr['EmpID'] = $emplIdInt;
$resultCsvLineArr['Date'] = $dateStr;
if(!isset($signleIoArr['C/In']) || empty($signleIoArr['C/In'])) {
$timeIn = '';
} else {
$timeIn = $signleIoArr['C/In'];
}
if(!isset($signleIoArr['C/Out']) || empty($signleIoArr['C/Out'])) {
$timeOut = '';
} else {
$timeOut = $signleIoArr['C/Out'];
}
$resultCsvLineArr['timeIn'] = $timeIn;
$resultCsvLineArr['timeOut'] = $timeOut;
$resultCsvArr[] = $resultCsvLineArr;
}
}
echo "--- Array Result ---\n";
var_export($resultCsvArr);
//get header line as arry of column names
//from the keys of the first array
$head = array_keys($resultCsvArr[0]);
//put arr of header as 1st sting to csv string
$csvStr = implode(',',$head) . "\n";
//put all the rest in result sting
foreach($resultCsvArr as $resultEntryArr) {
$csvStr .= implode(',',$resultEntryArr) . "\n";
}
// file_put_contents('path-to-file', $csvStr);
echo "\n\n --- CSV Result ---\n";
print_r($csvStr);
gives output:
--- Array Result ---
array (
0 =>
array (
'Name' => '"Soriano, Jhoniel"',
'EmpID' => 901,
'Date' => '05/03/2019',
'timeIn' => '',
'timeOut' => '1:01:03',
),
1 =>
array (
'Name' => '"Soriano, Jhoniel"',
'EmpID' => 901,
'Date' => '05/04/2019',
'timeIn' => '2:01:03',
'timeOut' => '3:01:03',
),
2 =>
array (
'Name' => '"Soriano, Jhoniel"',
'EmpID' => 901,
'Date' => '05/06/2019',
'timeIn' => '4:01:03',
'timeOut' => '5:01:03',
),
3 =>
array (
'Name' => '"Soriano, Jhoniel"',
'EmpID' => 901,
'Date' => '05/07/2019',
'timeIn' => '6:01:03',
'timeOut' => '',
),
)
--- CSV Result ---
Name,EmpID,Date,timeIn,timeOut
"Soriano, Jhoniel",901,05/03/2019,,1:01:03
"Soriano, Jhoniel",901,05/04/2019,2:01:03,3:01:03
"Soriano, Jhoniel",901,05/06/2019,4:01:03,5:01:03
"Soriano, Jhoniel",901,05/07/2019,6:01:03,
use:
file_put_contents('path-to-file', $csvStr);
at the end to save the csv to file.

Related

Create CSV with dynamic grouped headers in PHP from array

Could someone please assist in achieving that follow tasks please?
How to create a CSV export from a multidimensional array, but to have dynamic grouped column headings
Array (
[0] => Array ( [months] => 06/2020 [hours] => 202 [skill] => 5 )
[1] => Array ( [months] => 06/2020 [hours] => 563.5 [skill] => 6 )
[2] => Array ( [months] => 07/2020 [hours] => 140.5 [skill] => 6 )
[3] => Array ( [months] => 07/2020 [hours] => 522.5 [skill] => 5 )
)
So the output on the CSV would be like
+----------------------------+------------+--------+
| | Skill 6 |Skill 5 |
+----------------------------+------------+--------+
| 06/2020 | 563.5 | 202 |
+----------------------------+------------+--------+
| 07/2020 | 140.5 | 522.5 |
+----------------------------+------------+--------+
Added CSV output I have so far
Current CSV Element of the code
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=result_file.csv");
header("Pragma: no-cache");
header("Expires: 0");
// Building $data_array from DB
foreach ($data_array as $subarray) {
$tempKey = $subarray['skill'].$subarray['months'];
$subarray['hours'] = str_replace(',', '', $subarray['hours']);
if (isset($result[$tempKey])) {
$result[$tempKey]['hours'] += $subarray['hours'];
} else {
$result[$tempKey] = $subarray;
}
}
// CSV Output
outputCSV($result);
function outputCSV($result) {
$output = fopen("php://output", "w");
foreach ($result as $row) {
fputcsv($output, $row);
}
fclose($output);
}
any help would be greatly appreciated, TIA
Question edited
Pretty sure if I thought about this for a bit I could improve it but it seems like it gets the right answer
$in = [
[ 'months' => '06/2020', 'hours' => 202, 'skill' => 5 ],
[ 'months' => '06/2020', 'hours' => 563.5, 'skill' => 6 ],
[ 'months' => '07/2020', 'hours' => 140.5, 'skill' => 6 ],
[ 'months' => '07/2020', 'hours' => 522.5, 'skill' => 5 ]
];
$firstTitle = 'Month';
$months = [];
$skills = [$firstTitle=>1];
// make an array keyed on the date
foreach ( $in as $t) {
$months[$t['months']]['skill'.$t['skill']] = $t['hours'];
$skills['skill'.$t['skill']] = 1;
}
// sort skills into assending order
ksort($skills);
// open a file
$xl = fopen('excelfile.csv', 'w');
// echo title line from the skills array
fputcsv($xl, array_keys($skills));
// build csv line with skills in the correct order
foreach ($months as $date => $m){
// build array in correct sorted order
$t = [];
$t[] = $date;
foreach ($skills as $skill => $x) {
if ( $skill != $firstTitle) $t[] = $m[$skill];
}
fputcsv($xl,$t);
}
RESULT
Month,skill5,skill6
06/2020,202,563.5
07/2020,522.5,140.5
You're basically just aggregating the skill values by month and then outputting those aggregated values. This is not difficult, but you've got to be clear about what you're doing. One common reason I see new players get confused is that they're trying to use the most compact code possible, which makes it hard to keep track of what's happening. Be verbose, name things clearly, and comment your code relentlessly. You'll have a much easier time seeing why something isn't working, and your code will be much more maintainable. Write your code like someone else is going to be maintaining it. That someone else may be you in five years.
<?php
$dataArray = [
['months' => '06/2020', 'hours' => '202', 'skill' => '5'],
['months' => '06/2020', 'hours' => '563.5', 'skill' => '6'],
['months' => '06/2020', 'hours' => '303.7', 'skill' => '6'],
['months' => '08/2020', 'hours' => '123.5', 'skill' => '8'],
['months' => '07/2020', 'hours' => '140.5', 'skill' => '6'],
['months' => '07/2020', 'hours' => '522.5', 'skill' => '5'],
['months' => '08/2020', 'hours' => '123.5', 'skill' => '6']
];
/*
* Break out your formatting into functions so that it's re-usable and doesn't clutter up your logic
*/
function formatHours($hourString)
{
$hourString = str_replace(',', '', $hourString);
return floatval($hourString);
}
function buildSkillKey($skillValue)
{
return 'Skill '.$skillValue;
}
// Set up buffers for our skills and month values
$skills = [];
$buffer = [];
foreach($dataArray as $currRow)
{
//Format the hour value
$currHours = formatHours($currRow['hours']);
//Create key for the skill.
$skillKey = buildSkillKey($currRow['skill']);
/*
* Add the skill to the skill buffer. Using the value as the key is an easy way to both prevent duplicates
* without having to implement any logic, and have automatic alpha sorting
*/
$skills[$skillKey] = $skillKey;
// Set up an array for the month value if we don't have one already
if(!array_key_exists($currRow['months'], $buffer))
{
$buffer[$currRow['months']] = [];
}
/*
* If you don't have multiple month/skill entries that you need to aggregate, remove this condition
* and simply set the value in the buffer rather than adding with +=
*/
if(!array_key_exists($skillKey, $buffer[$currRow['months']]))
{
$buffer[$currRow['months']][$skillKey] = 0;
}
$buffer[$currRow['months']][$skillKey] += $currHours;
}
// Define a string for the months column header
$monthColumnTitle = '';
// Create the header row by combining the month header and the skills buffer
$header = array_merge([$monthColumnTitle], $skills);
// Open an output handle and send the header
$outputHandle = fopen("skills.csv", "w");
fputcsv($outputHandle, $header);
// Spin through the buffer
foreach($buffer as $currMonth=>$currSkillValues)
{
// Initialize an output array with the month in the first position
$currOutput = [$currMonth];
// Iterate through the skill buffer
foreach($skills as $currSkillLabel)
{
/*
* If we have a value for this skill, add it to the output row, otherwise insert an empty string.
*
* If you prefer to send zeros rather than empty strings, you can just set the field value to
* $currSkillValues[$currSkillLabel], since we initialized all skills with zeroes when building
* the value buffer.
*/
$currFieldValue = (!empty($currSkillValues[$currSkillLabel])) ? $currSkillValues[$currSkillLabel]:'';
$currOutput[] = $currFieldValue;
}
// Send the row
fputcsv($outputHandle, $currOutput);
}

Remove dates array between start date and end date in php

I want to find an optimized way to remove dates between start date and end date in php, below how i handle it but seems timeout when there is too many days :
/**
* Get list of dates from start date and end date
* #param {string} start
* #param {string} end
* #param {string} format
* #return array
*/
function _getDatesFromRange($start, $end, $format = 'd/m/Y') {
// Declare an empty array
$array = array();
// Variable that store the date interval
// of period 1 day
$interval = new DateInterval('P1D');
$realEnd = DateTime::createFromFormat('Y-m-d', $end);
$realEnd->add($interval);
$period = new DatePeriod(DateTime::createFromFormat('Y-m-d', $start), $interval, $realEnd);
// Use loop to store date into array
foreach($period as $date) {
$array[] = $date->format($format);
}
// Return the array elements
return $array;
}
/**
* Flat an array
* #param {array} array
* #return array
*/
function _flatten($array) {
$return = array();
array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
return $return;
}
// List of dates
$bookings = array(
array(
'bookable' => 'no',
'from' => '2020-08-01',
'to' => '2020-08-05'
),
array(
'bookable' => 'no',
'from' => '2020-08-15',
'to' => '2020-08-18'
),
array(
'bookable' => 'yes',
'from' => '2020-08-01',
'to' => '2020-08-31'
)
);
So to list all dates and get bookable list, i do like this :
foreach($bookings as $booking){
if($booking['bookable'] === 'yes'){
// Get an array of list of dates between start and end
$bookable[] = _getDatesFromRange($booking['from'], $booking['to']);
} else {
$not_bookable[] = _getDatesFromRange($booking['from'], $booking['to']);
}
}
if(is_array($bookable) && is_array($not_bookable)) {
$output = array_diff(_flatten($bookable), _flatten($not_bookable));
print_r($output);
}
You can test all from this url bookable dates demo, i have 2000 products and some products have a large intervals between start and end date like below, and in this case i get timeout execution, so how i can optimise above code ?
$bookings = array(
array(
'bookable' => 'no',
'from' => '2020-08-01',
'to' => '2020-08-05'
),
array(
'bookable' => 'no',
'from' => '2020-08-15',
'to' => '2020-08-18'
),
array(
'bookable' => 'yes',
'from' => '2050-08-01',
'to' => '2050-08-31'
)
);
Thanks for you helps

Better way to dynamically access values in nested array

I need a way to dynamically access values in a nested array using an index map. What i want to achieve is looping over an array with data and extract some values that can be in any level of the nesting and save it to a bi-dimensional array.
So far I've come up with the following code, which works quite well, but I was wondering if there is a more efficient way to do this.
<?php
// Sample data
$array = array();
$array[0]['code'] = "ABC123";
$array[0]['ship'] = array("name" => "Fortune", "code" => 'FA');
$array[0]['departure'] = array("port" => "Amsterdam", "code" => "AMS");
$array[0]['document'] = array("type" => "Passport", "data" => array("valid" => '2022-03-18', 'number' => 'AX123456') );
$array[1]['code'] = "QWERT67";
$array[1]['ship'] = array("name" => "Dream", "code" => 'DR');
$array[1]['departure'] = array("port" => "Barcelona", "code" => "BRC");
$array[1]['document'] = array("type" => "Passport", "data" => array("valid" => '2024-12-09', 'number' => 'DF908978') );
// map of indexes of $array I need in my final result array. The levels of the nested indexes is subdivided by ":"
$map = array("code", "ship:name", "departure:port", "document:type", "document:data:number");
$result = array();
// loop array for rows of data
foreach($array as $i => $row){
// loop map for indexes
foreach($map as $index){
// extract specific nested values from $row and save them in 2-dim array $result
$result[$i][$index] = xpath_array($index, $row);
}
}
// print out result
print_r($result);
// takes path to value in $array and returns given value
function xpath_array($xpath, $array){
$tmp = array();
// path is subdivded by ":"
$elems = explode(":", $xpath);
foreach($elems as $i => $elem){
// if first (or ony) iteration take root value from array and put it in $tmp
if($i == 0){
$tmp = $array[$elem];
}else{
// other iterations (if any) dig in deeper into the nested array until last item is reached
$tmp = $tmp[$elem];
}
}
// return found item (can be value or array)
return $tmp;
}
Any suggestion?
This was quite tricky for me, i used Recursive function, first we normalize array keys to obtain key as you want like this document:type, then we normalize array to obtain all at same level :
/**
* #param array $array
* #param string|null $key
*
* #return array
*/
function normalizeKey(array $array, ?string $key = ''): array
{
$result = [];
foreach ($array as $k => $v) {
$index = !empty($key) && !\is_numeric($key) ? $key.':'.$k : $k;
if (true === \is_array($v)) {
$result[$k] = normalizeKey($v, $index);
continue;
}
$result[$index] = $v;
}
return $result;
}
/**
* #param array $item
* #param int $level
*
* #return array
*/
function normalizeStructure(array $item, int $level = 0): array
{
foreach ($item as $k => $v) {
$level = isset($v['code']) ? 0 : $level;
if (true === \is_array($v) && 0 === $level) {
$item[$k] = normalizeStructure($v, ++$level);
continue;
}
if (true === \is_array($v) && 0 < $level) {
$item = \array_merge($item, normalizeStructure($v, ++$level));
unset($item[$k]);
continue;
}
}
return $item;
}
$data = normalizeStructure(normalizeKey($array));
I edited your data set to add more nests:
// Sample data
$array = array();
$array[0]['code'] = "ABC123";
$array[0]['ship'] = array("name" => "Fortune", "code" => 'FA');
$array[0]['departure'] = array("port" => "Amsterdam", "code" => "AMS");
$array[0]['document'] = array("type" => "Passport", "data" => array("valid" => '2022-03-18', 'number' => 'AX123456'));
$array[1]['code'] = "QWERT67";
$array[1]['ship'] = array("name" => "Dream", "code" => 'DR');
$array[1]['departure'] = array("port" => "Barcelona", "code" => "BRC");
$array[1]['document'] = array("type" => "Passport", "data" => array("valid" => '2024-12-09', 'number' => 'DF908978', 'check' => ['number' => '998', 'code' => 'itsWell', 'inception' => ['border' => 'finalInception']]));
With these data, you should finally receive this result:
/*
Array
(
[0] => Array
(
[code] => ABC123
[ship:name] => Fortune
[ship:code] => FA
[departure:port] => Amsterdam
[departure:code] => AMS
[document:type] => Passport
[document:data:valid] => 2022-03-18
[document:data:number] => AX123456
)
[1] => Array
(
[code] => QWERT67
[ship:name] => Dream
[ship:code] => DR
[departure:port] => Barcelona
[departure:code] => BRC
[document:type] => Passport
[document:data:valid] => 2024-12-09
[document:data:number] => DF908978
[document:data:check:number] => 998
[document:data:check:code] => itsWell
[document:data:check:inception:border] => finalInception
)
)
*/
Recursivity seems to be like Inception, everything is nested and you can lose your mind in 😆, mine was already lost in.

Searching for a value in an array using PHP

I have a list of users in my mongodb database, which can then follow each other -pretty standard. Using php I want to check if a specific user is following another user. My data looks like this.
array (
'_id' => ObjectId("56759157e1095db549d63af1"),
'username' => 'Joe',
'following' =>
array (
0 =>
array (
'username' => 'John',
),
1 =>
array (
'username' => 'Tom',
),
),
)
array (
'_id' => ObjectId("56759132e1095de042d63af4"),
'username' => 'Tom',
'following' =>
array (
0 =>
array (
'username' => 'Joe',
),
1 =>
array (
'username' => 'John',
),
2 =>
array (
'username' => 'Sam',
),
),
)
I want a query that will check if Joe is following Sam (which he's not) - so it would produce no results. However, if I was to query the database to check if Tom was following Sam, then it would produce a result to indicate he is (because he is). Do you know how I would do this in PHP? I've experimented with Foreach loops, but I haven't been able to get the results I want.
Make it by DB query, by php it will take more resources
Still if you want by php you can make it so
$following=false;
foreach($data as $v) if ($v['username'] == 'Joe') {
foreach($v['following'] as $v1) if (in_array('Sam', $v1)) {
$following=true;
break 2;
}
}
echo $following;
Such queries are best done in SQL, but if you insist on a PHP-based solution I would suggest to turn the data structure into items keyed by name. Once you have that it is a piece of cake to find relationships:
function organisePersons($data) {
$persons = array();
foreach($data as $person) {
$list = array();
foreach($person["following"] as $following) {
$list[$following["username"]] = $following["username"];
}
$person["following"] = $list;
$person["followedBy"] = array();
$persons[$person["username"]] = $person;
}
// link back to get all "followedBy":
// You can skip this block if you don't need "followedBy":
foreach ($persons as $person) {
foreach($person["following"] as $following) {
echo $person["username"] . " f. $following<br>";
if (!isset($persons[$following])) {
$persons[$following] = array(
"_id" => null, // unknown
"username" => $following,
"following" => array(),
"followedBy" => array()
);
}
$persons[$following]["followedBy"][] = $person["username"];
}
}
// return the new structure
return $persons;
}
So first call the function above with the data you have:
$persons = organisePersons($data);
And then you can write this:
if (isset($persons["Joe"]["following"]["Sam"])) {
echo "Joe is following Sam"; // not in output
};
if (isset($persons["Tom"]["following"]["Sam"])) {
echo "Tom is following Sam"; // in output
};
But also:
echo "Tom is following " . implode($persons["Tom"]["following"], ", ");
// Output: Tom is following Joe, John, Sam
And even the reverse question "Tom is followed by who?":
echo "Tom is followed by " . implode($persons["Tom"]["followedBy"], ", ");
// Output: Tom is followed by Joe

Using an array value to retrieve from another array

I have created an array, one of the is intended to be a string used by php to display a field from a record retrieved from sqlite3.
My problem is that ... it doesn't.
The array is defined, "1" being the first database field, and "2" is the second database field:
EDIT : I have re-defined the problem as a script so you can see the whole thing:
//If I have an array (simulating a record retrieved from database):
$record = array(
name => 'Joe',
comments => 'Good Bloke',
);
//then I define an array to reference it:
$fields = array(
1 => array(
'db_index' => 'name',
'db_type' => 'TEXT',
'display' => '$record["name"]',
'form_label' => 'Name',
),
2 => array(
'db_index' => 'comments',
'db_type' => 'TEXT',
'display' => '$record["comments"]',
'form_label' => 'Comments',
),
);
//If I use the lines:
print "expected output:\n";
print " Name = " . $record["name"] ."\n";
print " Comments = " . $record["comments"] ."\n";
//I display the results from the $record array correctly.
//However if I try & use the fields array with something like:
Print "Output using Array values\n";
foreach($GLOBALS["fields"] as $field)
{
$label = $field['form_label'];
$it = $field['display'];
$line = "\"$label = \" . $it .\"\n\"";
print $line;
}
Output:
Expected output:
Name = Joe
Comments = Good Bloke
Output using Array values:
Name = $record["name"]
Comments = $record["comments"]
Don't call variable from string. Just concatenate it :
foreach($GLOBALS["fields"] as $field){
$label = $field['form_label'];
$it = $field['display'];
eval("$it = ".$it);
$line = $label." = ".$it."\n";
print $line;
}
Well, how do it looks ?

Categories