I am very new to PHP (coming from JS) so am having trouble debugging this issue.
I have imported a .csv to render to a html table and am trying to retrieve a column so I can order the table. The table contains 5 headings (Date, TransactionNumber, CustomerNumber, Reference, Amount). I can retrieve all of the values except the Date column. That just returns an empty value.
<?php
$rows = array_map('str_getcsv', file('BankTransactions.csv'));
$header = array_shift($rows);
$csv = array();
foreach ($rows as $row) {
$csv[] = array_combine($header, $row);
}
print_r($csv[0]['Date']);
print_r("\n")
?>
// .csv
Date,TransactionNumber,CustomerNumber,Reference,Amount
2016-12-10 1:54PM,NUF5V6PT3U,5156,Purchase at JB HiFi,-2498
2016-12-4 4:54AM,J82964EFPS,2347,Refund,5424
2016-12-12 5:25PM,ZUFBQGCKTK,5683,Fee Refund,254
2016-12-01 12:00AM,XHNCASYLBR,2347,Purchase at Coles,-8873
2016-11-23 10:34PM,S98EBHDWG3,3423,Wages,198700
2017-09-23 9:34AM,MPNQYKVJ3G,4657,Purchase at Chemist Warehouse,-584
2015-11-23 10:34PM,74CQKEGSHB,2173,Refund,-3514
2015-11-23 10:35PM,WPTJMNVH4U,4527,Purchase at Hungry Monkey,45245
2017-01-01 12:00AM,U6BD3M75FD,7577,Interest,2778
// Array received from `.csv`
Array
(
[0] => Array
(
[Date] => 2016-12-10 1:54PM
[TransactionNumber] => NUF5V6PT3U
[CustomerNumber] => 5156
[Reference] => Purchase at JB HiFi
[Amount] => -2498
)
[1] => Array
(
[Date] => 2016-12-4 4:54AM
[TransactionNumber] => J82964EFPS
[CustomerNumber] => 2347
[Reference] => Refund
[Amount] => 5424
)
[2] => Array
(
[Date] => 2016-12-12 5:25PM
[TransactionNumber] => ZUFBQGCKTK
[CustomerNumber] => 5683
[Reference] => Fee Refund
[Amount] => 254
)
[3] => Array
(
[Date] => 2016-12-01 12:00AM
[TransactionNumber] => XHNCASYLBR
[CustomerNumber] => 2347
[Reference] => Purchase at Coles
[Amount] => -8873
)
[4] => Array
(
[Date] => 2016-11-23 10:34PM
[TransactionNumber] => S98EBHDWG3
[CustomerNumber] => 3423
[Reference] => Wages
[Amount] => 198700
)
[5] => Array
(
[Date] => 2017-09-23 9:34AM
[TransactionNumber] => MPNQYKVJ3G
[CustomerNumber] => 4657
[Reference] => Purchase at Chemist Warehouse
[Amount] => -584
)
[6] => Array
(
[Date] => 2015-11-23 10:34PM
[TransactionNumber] => 74CQKEGSHB
[CustomerNumber] => 2173
[Reference] => Refund
[Amount] => -3514
)
[7] => Array
(
[Date] => 2015-11-23 10:35PM
[TransactionNumber] => WPTJMNVH4U
[CustomerNumber] => 4527
[Reference] => Purchase at Hungry Monkey
[Amount] => 45245
)
[8] => Array
(
[Date] => 2017-01-01 12:00AM
[TransactionNumber] => U6BD3M75FD
[CustomerNumber] => 7577
[Reference] => Interest
[Amount] => 2778
)
)
Your CSV file is probably encoded in UTF-8 with a BOM, Byte Order Mark.
PHP does (still) not handle BOMs properly when reading files, so the very first line you read from the file will still contain it at the start, and therefor the first column value will also still contain it. So your key inside the $csv array is not actually Date, but [BOM]Date, but you don’t see that in the print_r output (a BOM isn’t actually “visible” per se.)
See How to remove multiple UTF-8 BOM sequences or https://gist.github.com/chrisguitarguy/6096271 for suggestions how the BOM can be removed.
You need to fetch the transaction for each field. Here: https://www.php.net/manual/en/function.fgetcsv.php
I am using the exact same CSV file and made a solution for an interview.
The CSV file's can be tested on the below link:
https://paduademo.azurewebsites.net/
<?php foreach ($transactions as $transaction) : ?>
<tr>
<td><?php echo $transaction['Date']; ?></td>
<td><?php echo $transaction['TransactionNumber']; ?></td>
<td><?php echo ($transaction['Valid'])? 'Yes': 'No'; ?></td>
<td><?php echo $transaction['CustomerNumber']; ?></td>
<td><?php echo $transaction['Reference']; ?></td>
<td><span class="<?php echo ($transaction['type'] == 'Credit')? 'text-danger': 'text-success'; ?>"><?php echo (($transaction['type'] == 'Credit')? '-': '') . '$' . $transaction['Amount']; ?></span></td>
</tr>
<?php endforeach; ?>
The screenshot is below:
Related
I have an array generated by an API i use a cpanel hosting with php 5.6.
I tried a lot of combination but is not working
The array are generated by emag marketplace api.
The code looks like
Array
(
[isError] =>
[messages] => Array
(
)
[results] => Array
(
[0] => Array
(
[vendor_name] => WISE COMPUTER SRLD
[id] => 2003677675
[parent_id] =>
[date] => 2017-05-21 10:55:18
[payment_mode] => RAMBURS
[payment_mode_id] => 1
[delivery_mode] => CURIER RO
[observation] =>
[status] => 4
[payment_status] => 0
[customer] => Array
(
[id] => 994041
[mkt_id] => 994041
[name] => Cristina Manuela Dancas
[company] => Cristina Manuela Dancas
[gender] =>
[phone_1] => 0743073616
[phone_2] =>
[phone_3] =>
[registration_number] =>
[code] =>
[email] =>
[billing_name] =>
[billing_phone] =>
[billing_country] => RO
[billing_suburb] => Bucuresti
[billing_city] => Sectorul 1
[billing_locality_id] => 2
[billing_street] => Str. Aviator Sanatescu nr. 57, parter, Ap1
[billing_postal_code] =>
[shipping_country] => RO
[shipping_suburb] => Bucuresti
[shipping_city] => Sectorul 1
[shipping_locality_id] => 2
[shipping_postal_code] =>
[shipping_contact] => Cristina Manuela Dancas
[shipping_phone] => 0743073616
[created] => 2017-05-21 10:55:19
[modified] => 2017-05-21 10:56:21
[bank] =>
[iban] =>
[legal_entity] => 0
[fax] =>
[is_vat_payer] => 1
[liable_person] =>
[shipping_street] => Str. Aviator Sanatescu nr. 57, parter, Ap1
)
I what to use php to convert in a HTML table.
Need some help. If you need more information please leave a message.
This is my quick solution to make a HTML table from a PHP array.
The essence is although, that a two-dimensional array, makes into a table that makes sense. Your array seems to be more complex, so converting into a useful table will probably take a bit more effort.
$data = array( array("ID","Firstname","Lastname","Phone"),
array("1","John","Jenkins","+91375953"),
array("2","Eduard","Kenny","+7244277"),
array("3","Anita","Beaumont","+427427427"),
array("4","Wanda","Wade","+274274247"),
array("4","Sarah","Colon","+835835"),
);
echo '<table border="1">';
foreach($data as $row) {
echo '<tr>';
foreach($row as $cell) {
echo '<td>'.$cell.'</td>';
}
echo '</tr>';
}
echo '</table>';
I have an array and when I do
$array = json_decode($response, true);
print_r($array);
This is what I get from an array.
Array ( [data] => Array ( [0] => Array ( [id] => accenture [type] => companies [attributes] => Array ( [name] => Accenture [description] => Accenture is a global management consulting, technology services and outsourcing company, with more than 293,000 people serving clients in more than 120 countries. Combining unparalleled experience, comprehensive capabilities across all industries and business functions, and extensive research on the world’s most successful companies, Accenture collaborates with clients to help them become high-performance businesses and governments. The company generated net revenues of US$xxx for the fiscal year ended Aug. 31, 2013. Its home page is www.some-url.com. [employee_count_range] => 10001+ [founded_year] => 1989 [industries] => Array ( [0] => Information Technology & Services ) [website_url] => www.some-url.com [logo] => https://some-url/logo.png [square_logo] => https://some-url/square_logo.png [followed] => [claimed_status] => 1 [last_reviewed_at] => ) ) [1] => Array ( [id] => accenture-banglore [type] => companies [attributes] => Array ( [name] => Accenture, Banglore [description] => [employee_count_range] => [founded_year] => [industries] => [website_url] => [logo] => [square_logo] => [followed] => [claimed_status] => 1 [last_reviewed_at] => ) ) [2] => Array ( [id] => accenture-gmbh [type] => companies [attributes] => Array ( [name] => Accenture GmbH [description] => [employee_count_range] => [founded_year] => [industries] => [website_url] => [logo] => [square_logo] => [followed] => [claimed_status] => 1 [last_reviewed_at] => ) )
I tried with foreach loop to create a table and show the data in the table. This is how I try but I get an error "Invalid argument supplied for foreach()"
echo '<table>';
foreach($array as $result){
echo '<tr>';
echo '<td>'.$result->id.'</td>';
echo '<td>'.$result->name.'</td>';
echo '<td>'.$result->description.'</td>';
echo '<td>'.$result->funded_year.'</td>';
echo '</tr>';
}
echo '</table>';
Can anyone help me show the data in the table?
Your data for HTML table is inside data array key.
You should write:
foreach($array['data'] as $result){
or even better:
$array = json_decode($response, true);
$resultArray = isset($array['data']) ? $array['data'] : [];
echo '<table>';
foreach($resultArray as $result){
echo '<tr>';
echo '<td>'.(isset($result['id']) ? $result['id'] : '-') .'</td>';
echo '<td>'.(isset($result['attributes']['name']) ? $result['attributes']['name'] : '-').'</td>';
echo '<td>'.(isset($result['attributes']['description']) ? $result['attributes']['description'] : '-').'</td>';
echo '<td>'.(isset($result['attributes']['funded_year']) ? $result['attributes']['funded_year'] : '-').'</td>';
echo '</tr>';
}
echo '</table>';
http://php.net/manual/en/function.json-decode.php
I"m trying to traverse on an object i"m getting from openweather.com
without the foreach() i"m getting the right result. inside the foreach() i get an error.
the php code:
$contents = file_get_contents($url);
$clima=json_decode($contents,TRUE);
echo $clima['list'][5]['main']['temp']; // this one works
$i=0;
foreach($clima['list'] as $clima1) {
echo $clima1[$i]['dt']; // here i get PHP Notice: Undefined offset
echo $clima1[$i]['main']['temp']; //here i get PHP Notice: Undefined index: list
$i=$i+1;
}
the error that i get is:
PHP Notice: Undefined offset: 0 // the error is from 0 to 39 and there are 39 objects...
PHP Notice: Undefined index: list
the object beginning and ending part for sample:
Array ( [cod] => 200 [message] => 0.014 [cnt] => 40 [list] =>
Array ( [0] => Array ( [dt] => 1492732800 [main] => Array ( [temp] => 17.64 [temp_min] => 17.04 [temp_max] => 17.64 [pressure] => 1026.03 [sea_level] => 1031.21 [grnd_level] => 1026.03 [humidity] => 100 [temp_kf] => 0.6 ) [weather] => Array ( [0] => Array ( [id] => 800 [main] => Clear [description] => clear sky [icon] => 01n ) ) [clouds] => Array ( [all] => 0 ) [wind] => Array ( [speed] => 1.66 [deg] => 81.5008 ) [sys] => Array ( [pod] => n ) [dt_txt] => 2017-04-21 00:00:00 )
[38] => Array ( [dt] => 1493143200 [main] => Array ( [temp] => 19.72 [temp_min] => 19.72 [temp_max] => 19.72 [pressure] => 1026.92 [sea_level] => 1032.02 [grnd_level] => 1026.92 [humidity] => 87 [temp_kf] => 0 ) [weather] => Array ( [0] => Array ( [id] => 800 [main] => Clear [description] => clear sky [icon] => 01n ) ) [clouds] => Array ( [all] => 0 ) [wind] => Array ( [speed] => 6.95 [deg] => 10.5008 ) [sys] => Array ( [pod] => n ) [dt_txt] => 2017-04-25 18:00:00 )
[39] => Array ( [dt] => 1493154000 [main] => Array ( [temp] => 18.43 [temp_min] => 18.43 [temp_max] => 18.43 [pressure] => 1026.75 [sea_level] => 1031.91 [grnd_level] => 1026.75 [humidity] => 98 [temp_kf] => 0 ) [weather] => Array ( [0] => Array ( [id] => 800 [main] => Clear [description] => clear sky [icon] => 01n ) ) [clouds] => Array ( [all] => 0 ) [wind] => Array ( [speed] => 6.03 [deg] => 9.50076 ) [sys] => Array ( [pod] => n ) [dt_txt] => 2017-04-25 21:00:00 ) )
[city] => Array ( [id] => **** [name] => ***** [coord] => Array ( [lat] => **.**** [lon] => **.**** ) [country] => ** ) )
any help to understand my mistake will be appreciated
It seems, you loop "double". The counter inside the loop is the part, which you don't need, as you already loop over the array with foreach.
I think, the following code would be the better approach
$contents = file_get_contents($url);
$clima=json_decode($contents,TRUE);
echo $clima['list'][5]['main']['temp']; // this one works
foreach($clima['list'] as $clima1) {
echo $clima1['dt']; // here i get PHP Notice: Undefined offset
echo $clima1['main']['temp']; //here i get PHP Notice: Undefined index: list
}
That is because when you foreach over $clima['list'] you will get every values inside $clima['list']. Therefore, first, $clima1 = $clima['list'][0]. After that, $clima1 = $clima['list'][1]... Thus, $clima1 has neither 0 as an index nor 1 nor 2...
What you might do to see it more clearly is this :
foreach($clima['list'] as $key => $clima1)
And everytime, the $key will be your $id. Therefore, you can get rid of your $id and just do it like this :
foreach($clima['list'] as $id => $clima1)
When you run foreach($clima['list'] as $clima1) { ... each object in the loop ($clima1) is equal to $clima['list'][$i] so you don't need to manually put the $i in there.
If your really stuck I'd just run the loop like:
foreach($clima['list'] as $clima1) {
var_dump('<pre>' . $clima1 . '</pre>');
}
To see what the $clima1 variable really is.
I have a hierarchical data that I put in a array that I call $dt. Than I have a array that store the relationship between these data that I call $in. I have create a function that has as parameter, the initial index, level, array $dt an the array $in. I was debugging the function but I am not find why the subclass is lost during the process. The complete code is:
$dt = array(
41=>array( "pk"=>41,"parentPk"=>30,"name"=>"car1"),
15=>array("pk"=>15,"parentPk"=>11,"name"=>"food" ),
70=>array("pk"=>70,"parentPk"=>30,"name"=>"car3" ),
18=>array("pk"=>18,"parentPk"=>15,"name"=>"food1" ),
49=>array("pk"=>49,"parentPk"=>30,"name"=>"car2" ),
20=>array( "pk"=>20,"parentPk"=>15,"name"=>"food2"),
30=>array("pk"=>30,"parentPk"=>11,"name"=>"car" )
);
echo "<pre>";
print_r($dt);
echo "</pre>";
$in=array(11=>array(15,30),15=>array(18,20),30=>array(41,49,70));
echo "<pre>";
print_r($in);
echo "</pre>";
function fn_tree($parent_id, $level,$dt,$in) {
if(is_null($parent_id)){
$parent_id ="NULL";
}
if (isset($in[$parent_id])) {
foreach ($in[$parent_id] as $id) {
$pk=$in[$parent_id];
$arrEnd[$id]=str_repeat("-", $level*2) .$dt[$id]["name"];
fn_tree($id, $level + 1,$dt,$in,$arrEnd);
}
}
return $arrEnd;
}
$arrEcho = fn_tree(11, 0, $dt, $in);
echo "<br>";
echo "result";
echo "<br>";
echo "<pre>";
print_r($arrEcho);
echo "</pre>";
$desired = array(
15=>"food",
18=>"food1",
20=>"food2",
30=>"car",
41=>"car1",
49=>"car2",
70=>"car3"
);
echo "<br>";
echo "desired";
echo "<br>";
echo "<pre>";
print_r($desired);
echo "</pre>";
So why the function is losting the sub-classes?
Output is:
Array data
(
[41] => Array
(
[pk] => 41
[parentPk] => 30
[name] => car1
)
[15] => Array
(
[pk] => 15
[parentPk] => 11
[name] => food
)
[70] => Array
(
[pk] => 70
[parentPk] => 30
[name] => car3
)
[18] => Array
(
[pk] => 18
[parentPk] => 15
[name] => food1
)
[49] => Array
(
[pk] => 49
[parentPk] => 30
[name] => car2
)
[20] => Array
(
[pk] => 20
[parentPk] => 15
[name] => food2
)
[30] => Array
(
[pk] => 30
[parentPk] => 11
[name] => car
)
)
Array relationship
(
[11] => Array
(
[0] => 15
[1] => 30
)
[15] => Array
(
[0] => 18
[1] => 20
)
[30] => Array
(
[0] => 41
[1] => 49
[2] => 70
)
)
result
Array
(
[15] => food
[30] => car
)
desired
Array
(
[15] => food
[18] => food1
[20] => food2
[30] => car
[41] => car1
[49] => car2
[70] => car3
)
The clue to your problem is/should have been "Undefined variable: arrEnd." If you aren't running in an environment where you can see this warning, you should try to set up such an environment. If you are running in such an environment, you should play close attention to this and all other warnings.
I'm not sure if it is the convention here to just give a clue or a whole answer, but proceeding on to give a fairly complete answer: it seems that you intended to pass arrEnd in by reference, but did not pass it in at all.
Also, I'm a little confused by your desired output. Don't you in fact desire something with double dashes showing hierarchy, as below?
Array
(
[15] => food
[18] => --food1
[20] => --food2
[30] => car
[41] => --car1
[49] => --car2
[70] => --car3
)
As I can make an ordered descending by the query field bytes each IP. This is my array contains other fields as refered or other browsers ....
[_id] => MongoId Object (
[$id] => 528e6004b0a4191f698b4567
)
[FECHA] =>.........
[IP] => Array (
[0] => Array (
[Ip] => 172.17.10.
[conexiones] => 71
[bytes] => 122.75 KB
[media] => 1770.338
)
[1] => Array (
[Ip] => 192.168.6.145
[conexiones] => 79
[bytes] => 692.51 KB
[media] => 8976.3164
)
[2] => Array (
[Ip] => 172.17.108.3
[conexiones] => 2
[bytes] => 4.48 KB
[media] => 2294.5
)
[3] => Array (
[Ip] => 192.168.200.50
[conexiones] => 123
[bytes] => 6.10 MB
[media] => 52004.699186992
...............
This is my code:
$Filtro="IP";
$c = $collection->find(array('FECHA' => $Fecha), array($Filtro));
$cont = 1;
while ($c->hasNext()) {
$metodo = $c->getNext();
foreach ($metodo[$Filtro] as $f) {
?>
<tr>
<td><?= $cont++ ?></td>
<td><?= $f[$Filtro] ?></td>
<td><?= $f['conexiones'] ?></td>
<td><?= $f['bytes'] ?></td>
<td><?= $f['media'] ?></td></tr>
<?
}
}
Just shows me all data but unsorted. thanks