I make an event list with a maximum of 4 events, saved in its own jason files.
I wrote this code for the output.
JSON:
{"field1":"new york","field2":"1553404200","field3":1554415200}
CODE:
$jsonA = file_get_contents('code/data1.json');
$fieldsA = json_decode($jsonA, true);
$cityA = $fieldsA["field1"];
$dateStartA = $fieldsA["field2"];
$dateEndA = $fieldsA["field3"];
$jsonB = file_get_contents('code/data2.json');
$fieldsB = json_decode($jsonB, true);
$cityB = $fieldsB["field1"];
$dateStartB = $fieldsB["field2"];
$dateEndB = $fieldsB["field3"];
<div><?php echo $cityA . $dateStartA . " - " . $dateEndA?></div>
<div><?php echo $cityB . $dateStartB . " - " . $dateEndB?></div>
The problem is:
I have 4 events with each start and end date. So I have to do the same 8 times, but I do not want and should copy this code 8 times with a higher variable name...
In my project I have 13 fields and also 2 arrays to output the day and month name in my language. That's why it's so important not to copy everything 8 times.
I need a loop, but I do not know exactly how. I'm an absolute beginner, so please as simple as possible.
Great job with your attempt!
You might just want to write a foreach and read your files and store it in an array.
In your local server, you might just want to find the absolute path to your code folder. If you open your terminal, and CTRL+C code directory and CTRL+V in your terminal, you might see what your absolute path may look like. Then, paste upto before code directory in $server_path. Then, run the code, hopefully it would work.
function searchFilenames($array, $re)
{
return preg_grep('/' . preg_quote($re, '/') . '/i', $array);
}
$server_path = '/path/to/your/localserver/';
$dir = $server_path . 'code';
$filename_array = searchFilenames(glob($dir . "/*"), 'data');
$fields = array();
foreach ($filename_array as $key => $filename) {
$jsonA = file_get_contents($filename);
$values = json_decode($jsonA, true);
$fields[$key]["city"] = $values["field1"];
$fields[$key]["dateStart"] = $values["field2"];
$fields[$key]["dateEnd"] = $values["field3"];
}
var_dump($fields);
Output
array(8) {
[0]=>
array(3) {
["city"]=>
string(8) "new york"
["dateStart"]=>
string(10) "1553404200"
["dateEnd"]=>
int(1554415200)
}
[1]=>
array(3) {
["city"]=>
string(6) "boston"
["dateStart"]=>
string(10) "1553404200"
["dateEnd"]=>
int(1554415200)
}
[2]=>
array(3) {
["city"]=>
string(7) "chicago"
["dateStart"]=>
string(10) "1553404200"
["dateEnd"]=>
int(1554415200)
}
[3]=>
array(3) {
["city"]=>
string(13) "washington dc"
["dateStart"]=>
string(10) "1553404200"
["dateEnd"]=>
int(1554415200)
}
[4]=>
array(3) {
["city"]=>
string(5) "miami"
["dateStart"]=>
string(10) "1553404200"
["dateEnd"]=>
int(1554415200)
}
[5]=>
array(3) {
["city"]=>
string(10) "los angles"
["dateStart"]=>
string(10) "1553404200"
["dateEnd"]=>
int(1554415200)
}
[6]=>
array(3) {
["city"]=>
string(7) "seattle"
["dateStart"]=>
string(10) "1553404200"
["dateEnd"]=>
int(1554415200)
}
[7]=>
array(3) {
["city"]=>
string(6) "austin"
["dateStart"]=>
string(10) "1553404200"
["dateEnd"]=>
int(1554415200)
}
}
Related
i have two csv files: one contracts data and the other containing awarded contracts. I need to combine these two files using common field(contractname) and compute total amount of current awarded contracts.
Link to csv files:
https://github.com/younginnovations/problem-statements/tree/master/clean-up-contracts-data
I do get desired output bt undefined offset error comes up.
the code:unset(awards_info[$y][0]); does unsets the data but 'Undefined offset: 0' error occurs..
similarly the code $list_data[10]!=NULL also shows the same error
but both are producing desired output.
var_dump($awards_info):: produces following:
array(5) { [0]=> array(6) { [0]=> string(12) "contractName" [1]=> string(12) "contractDate" [2]=> string(14) "completionDate" [3]=> string(7) "awardee" [4]=> string(15) "awardeeLocation" [5]=> string(6) "Amount" } [1]=> array(6) { [0]=> string(15) "Contract-2070-3" [1]=> string(8) "5/9/2014" [2]=> string(9) "8/25/2014" [3]=> string(11) "SK Builders" [4]=> string(5) "Banke" [5]=> string(6) "200000" } [2]=> array(6) { [0]=> string(15) "Contract-2070-5" [1]=> string(9) "3/18/2014" [2]=> string(8) "4/8/2014" [3]=> string(24) "S engineering industries" [4]=> string(9) "Makwanpur" [5]=> string(6) "300000" } [3]=> array(6) { [0]=> string(15) "Contract-2070-9" [1]=> string(8) "3/6/2014" [2]=> string(8) "4/6/2014" [3]=> string(24) "Gourishankar nirman sewa" [4]=> string(8) "Lalitpur" [5]=> string(6) "400000" } [4]=> array(6) { [0]=> string(16) "Contract-2070-10" [1]=> string(8) "2/6/2014" [2]=> string(9) "6/16/2014" [3]=> string(11) "SK Builders" [4]=> string(5) "Banke" [5]=> string(6) "400000" } }
$file_contract=fopen('contracts.csv','r');
$file_awards=fopen('awards.csv','r');
while(($data=fgetcsv($file_contract))!=FALSE){
$contracts_info[]=$data;
}
while(($data=fgetcsv($file_awards))!=FALSE){
$awards_info[]=$data;
}
$con_count=count($contracts_info);
for($x=0;$x<$con_count;$x++){
if($x==0){
unset($awards_info[0][0]);
$data[$x]=array_merge($contracts_info[0],$awards_info[0]);
}
else{
$check=0;
$award_count=count($awards_info);
for($y=1;$y<$award_count;$y++){
if($awards_info[$y][0]==$contracts_info[$x][0]){
unset($awards_info[$y][0]);
$data[$x]=array_merge($contracts_info[$x],$awards_info[$y]);
$check=1;
}
}
if($check==0){
$data[$x]=$contracts_info[$x];
}
}
}
$final_data=fopen('final.csv','w');
foreach($data as $list_data){
fputcsv($final_data,$list_data);
}
fclose($final_data);
$c=0;
foreach ($data as $list_data){
if(($list_data[1]=='Current') && ($list_data[10]!=NULL))
{
$c+=$list_data[12];
}
}
echo $c;
You can just add the content file in the new file, without parsing files :
$fp = fopen('final.csv','w');
fwrite($fp, file_get_contents('contracts.csv'));
fwrite($fp, file_get_contents('awards.csv'));
fclose($fp);
echo file_get_contents('final.csv');
ok it's a wrong way. So i try to rewrite the loop :
for($x=0; $x < count($contracts_info); $x++) {
$data[$x] = $contracts_info[$x];
if($x == 0) {
if(isset($awards_info[$x])) {
$data[$x] = array_merge($data[$x], $awards_info[$x]);
unset($awards_info[$x]);
}
} else {
foreach($awards_info as $y => $award_info_datas) {
if($award_info_datas[0] == $contracts_info[$x][0]) {
$data[$x] = array_merge($data[$x], $award_info_datas);
unset($awards_info[$y]);
break;
}
}
}
}
When I use my glob It lets me list files. I would like to be able to count the files but not the ones in my not count array();
When I echo the count it counts 3 but should only echo count 2 there is no other file.
How do I make sure counts correct?
<?php
class Count extends MX_Controller {
public function index() {
$name = glob(FCPATH . 'application/modules/admin/controllers/*/*.php');
$not_count = array(
FCPATH . 'application/modules/admin/controllers/common/dashboard.php',
FCPATH . 'application/modules/admin/controllers/common/footer.php',
FCPATH . 'application/modules/admin/controllers/common/header.php',
FCPATH . 'application/modules/admin/controllers/common/login.php',
FCPATH . 'application/modules/admin/controllers/common/logout.php',
FCPATH . 'application/modules/admin/controllers/common/menu.php',
FCPATH . 'application/modules/admin/controllers/common/register.php',
FCPATH . 'application/modules/admin/controllers/dashboard/customer_total.php',
FCPATH . 'application/modules/admin/controllers/dashboard/online.php',
FCPATH . 'application/modules/admin/controllers/dashboard/user_total.php',
FCPATH . 'application/modules/admin/controllers/error/permission.php'
);
var_dump($not_count);
echo "<br/>";
echo "<br/>";
var_dump($name);
// Not Counting Correct When Echo Out Puts 3 Should be 2
$filecount1 = count(array_diff($not_count, $name));
echo "<br/>";
echo "<br/>";
echo $filecount1;
}
}
Var Dump Not Count Array
array(11) { [0]=> string(14) "customer_total" [1]=> string(9) "dashboard" [2]=> string(6) "footer" [3]=> string(6) "header" [4]=> string(5) "login" [5]=> string(6) "logout" [6]=> string(4) "menu" [7]=> string(6) "online" [8]=> string(10) "permission" [9]=> string(8) "register" [10]=> string(10) "user_total" }
Var Dump All Files Out Put
array(13) { [0]=> string(95) "C:\Xampp\htdocs\project1\application/modules/admin/controllers/common/dashboard.php" [1]=> string(92) "C:\Xampp\htdocs\project1\application/modules/admin/controllers/common/footer.php" [2]=> string(92) "C:\Xampp\htdocs\project1\application/modules/admin/controllers/common/header.php" [3]=> string(91) "C:\Xampp\htdocs\project1\application/modules/admin/controllers/common/login.php" [4]=> string(92) "C:\Xampp\htdocs\project1\application/modules/admin/controllers/common/logout.php" [5]=> string(90) "C:\Xampp\htdocs\project1\application/modules/admin/controllers/common/menu.php" [6]=> string(94) "C:\Xampp\htdocs\project1\application/modules/admin/controllers/common/register.php" [7]=> string(103) "C:\Xampp\htdocs\project1\application/modules/admin/controllers/dashboard/Customer_total.php" [8]=> string(95) "C:\Xampp\htdocs\project1\application/modules/admin/controllers/dashboard/Online.php" [9]=> string(99) "C:\Xampp\htdocs\project1\application/modules/admin/controllers/dashboard/User_total.php" [10]=> string(95) "C:\Xampp\htdocs\project1\application/modules/admin/controllers/error/permission.php" [11]=> string(110) "C:\Xampp\htdocs\project1\application/modules/admin/controllers/extension/extension_permissions.php" [12]=> string(88) "C:\Xampp\htdocs\project1\application/modules/admin/controllers/user/user.php" }
Just use array_diff() to only count the difference like this:
echo count(array_diff($files, $ignore));
EDIT:
Your question is unclear, but I think you may want something like this:
echo count(array_filter(array_map(function($v)use($ignore){
return in_array(pathinfo(basename($v))["filename"], $ignore);
}, $files)));
Im new to json & php and I'm having some issues with json into php string
My json string looks like this
{"status":"OK","cards":
[{"id":100001,"name":"batman","image":11111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T11:37:07Z"},
{"id":100002,"name":"superman","image":111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:30:09Z"},
{"id":100003,"name":"catwoman","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:39:42Z"},
{"id":100004,"name":"bane","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-09-08T12:56:04Z"}
]}
So Far i have created my string
$json_raw = '{"status":"OK","cards": [{"id":100001,"name": .....
Decoded the json
$arr = json_decode($json_raw, TRUE);
I var_dump($arr);
then it returns
array(2) { ["status"]=> string(2) "OK" ["cards"]=> array(4) { [0]=> array(8) { ["id"]=> int(100001) ["name"]=> string(6) "batman" ["image"]=> int(11111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-08-15T11:37:07Z" } [1]=> array(8) { ["id"]=> int(100002) ["name"]=> string(8) "superman" ["image"]=> int(111111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-08-15T12:30:09Z" } [2]=> array(8) { ["id"]=> int(100003) ["name"]=> string(8) "catwoman" ["image"]=> int(1111111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-08-15T12:39:42Z" } [3]=> array(8) { ["id"]=> int(100004) ["name"]=> string(4) "bane" ["image"]=> int(1111111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-09-08T12:56:04Z" } } }
Now all I want to do is be able to use this data
e.g if name = batman then
I know this is a stupid question but I am struggling :(
Thank in Advance
json_decode() with TRUE as second parameter gives you an associative array. You need to access the correct index to do what you want.
To list the complete associative array with nice formatting, you can do:
echo '<pre>', print_r($arr), '</pre>';
Now, to access the name in your array:
$man = $arr['cards'][0]['name'];
To check if it's Batman (yay!):
if( isset($man) && $man == 'batman' ) {
# code ...
}
For getting the name of all similar names:
$man = $json['cards']['0']['name'];
for ($i=0; $i < count($json['cards']); $i++) {
echo $json['cards'][$i]['name']."\n";
}
See it live!
when you got the array
$arr = json_decode($json_raw, TRUE);
then check if cards key exist
if(array_key_exists('cards', $arr)){
foreach($arr['cards'] as $key=>$val){
echo $key; ///name, id..
echo $val; /// batman,...
if($key == 'name' && $val =='batman'){
//-------do your stuff
}
}
}
Try with:
$cards = $arr['cards'];
foreach($cards as $card) {
if($card['name'] == 'batman') echo 'Hello batman!';
}
EDIT:
Ok, so this worked for me using code above, try it yourself if you want:
<?php
$json_raw = '{"status":"OK","cards":
[{"id":100001,"name":"batman","image":11111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T11:37:07Z"},
{"id":100002,"name":"superman","image":111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:30:09Z"},
{"id":100003,"name":"catwoman","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:39:42Z"},
{"id":100004,"name":"bane","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-09-08T12:56:04Z"}
]}';
$arr = json_decode($json_raw, TRUE);
$cards = $arr['cards'];
foreach($cards as $card) {
if($card['name'] == 'batman') echo 'Hello batman!';
}
?>
I am creating a JQuery cycle for weather radar and warning images. I have the radar overlay functioning just fine. The directory containing the warning files contains 2 versions of each file but one has a similiar file names as the radar images. So I decided to use a str_replace to replace the one part of the filename from the radar images to the warning images. For some reason the str_replace is not working and I cannot for the life of me figure out why.
Thank you in advance for any help.
// Used to get radar images
echo '<div class="wp-forecast-img-cur">'."\n";
$matches = array();
preg_match_all("/(a href\=\")([^\?\"]*)(\")/i", get_text('http://radar.weather.gov/ridge/RadarImg/N0R/BOX/'), $matches);
foreach($matches[2] as $k => $match) {
if ($k < 1) continue;
echo '<img src="http://radar.weather.gov/ridge/RadarImg/N0R/BOX/' . $match . '" />'."\n";
}
echo '</div>'."\n";
// Used to get warning images
echo '<div class="wp-forecast-img-warn">'."\n";
$matches = array();
preg_match_all("/(a href\=\")([^\?\"]*)(\")/i", get_text('http://radar.weather.gov/ridge/RadarImg/N0R/BOX/'), $matches);
foreach($matches[2] as $k => $match) {
if ($k < 1) continue;
echo '<img src="http://radar.weather.gov/ridge/Warnings/Short/BOX/' . str_replace("NOR", "Warnings", $match) . '" />'."\n";
}
echo '</div>'."\n";
This line is just echoing the original file name and not replacing NOR with Warnings.
echo '<img src="http://radar.weather.gov/ridge/Warnings/Short/BOX/' . str_replace("NOR", "Warnings", $match) . '" />'."\n";
This is the get_text function in case it's needed.
function get_text($filename)
{
$fp_load = fopen("$filename", "rb");
if ( $fp_load )
{
while ( !feof($fp_load) )
{
$content .= fgets($fp_load, 8192);
}
fclose($fp_load);
return $content;
}
}
Variable Dump
array(32) {
[0]=> string(20) "/ridge/RadarImg/N0R/"
[1]=> string(25) "BOX_20130703_2220_N0R.gif"
[2]=> string(25) "BOX_20130703_2232_N0R.gif"
[3]=> string(25) "BOX_20130703_2238_N0R.gif"
[4]=> string(25) "BOX_20130703_2243_N0R.gif"
[5]=> string(25) "BOX_20130703_2249_N0R.gif"
[6]=> string(25) "BOX_20130703_2301_N0R.gif"
[7]=> string(25) "BOX_20130703_2306_N0R.gif"
[8]=> string(25) "BOX_20130703_2318_N0R.gif"
[9]=> string(25) "BOX_20130703_2324_N0R.gif"
[10]=> string(25) "BOX_20130703_2330_N0R.gif"
[11]=> string(25) "BOX_20130703_2335_N0R.gif"
[12]=> string(25) "BOX_20130703_2347_N0R.gif"
[13]=> string(25) "BOX_20130703_2353_N0R.gif"
[14]=> string(25) "BOX_20130703_2359_N0R.gif"
[15]=> string(25) "BOX_20130704_0004_N0R.gif"
[16]=> string(25) "BOX_20130704_0016_N0R.gif"
[17]=> string(25) "BOX_20130704_0022_N0R.gif"
[18]=> string(25) "BOX_20130704_0027_N0R.gif"
[19]=> string(25) "BOX_20130704_0033_N0R.gif"
[20]=> string(25) "BOX_20130704_0045_N0R.gif"
[21]=> string(25) "BOX_20130704_0056_N0R.gif"
[22]=> string(25) "BOX_20130704_0108_N0R.gif"
[23]=> string(25) "BOX_20130704_0114_N0R.gif"
[24]=> string(25) "BOX_20130704_0125_N0R.gif"
[25]=> string(25) "BOX_20130704_0137_N0R.gif"
[26]=> string(25) "BOX_20130704_0148_N0R.gif"
[27]=> string(25) "BOX_20130704_0154_N0R.gif"
[28]=> string(25) "BOX_20130704_0206_N0R.gif"
[29]=> string(25) "BOX_20130704_0211_N0R.gif"
[30]=> string(25) "BOX_20130704_0223_N0R.gif"
[31]=> string(25) "BOX_20130704_0229_N0R.gif"
}
I think that the str_replace does not work because the string you need to replace is not "NOR" but "N0R" (N-zero-R).
I have been given a textfile which contains data on time sheet. That line contains a name and a department and their time out/in.The code below allows me to display the entire textfile but I want to read in the values by name and department from file and want to display that .
<?php
$file = fopen("C:\Bhrugisha mam.txt","r") or exit("Unable to open file!");
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>
this is some data from my text file...
VCANTECH - Log Report
6 Bhrugisha Shah
Hr
Department: HR
August, 2011 Page 1 of 2
-----------------------------------------------------------------------------------------------------------------
Date : 01/Aug/2011 Shift : 1 ( 9:30:00 AM To 6:30:00 PM )
LOG TIME : 9:23:00 AM LOG TYPE : IN
LOG TIME : 1:55:00 PM LOG TYPE : OUT
LOG TIME : 2:18:00 PM LOG TYPE : IN
LOG TIME : 6:45:00 PM LOG TYPE : OUT
This should get you there
$input = fread( $file, filesize("PATHTOFILE"));
preg_match("%Department:[\s]{1,}[a-z]{1,}%i", $input, $department);
var_dump($department);
//OUTPUT array(1) { [0]=> array(1) { [0]=> string(22) "Department: HR" }
preg_match_all("%log time : [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2} (AM|PM) LOG TYPE : (IN|OUT)%i", $input, $matches);
var_dump($matches);
/*
OUTPUT
array(3) { [0]=> array(4) { [0]=> string(57) "LOG TIME : 9:23:00 AM LOG TYPE : IN" [1]=> string(58) "LOG TIME : 1:55:00 PM LOG TYPE : OUT" [2]=> string(57) "LOG TIME : 2:18:00 PM LOG TYPE : IN" [3]=> string(58) "LOG TIME : 6:45:00 PM LOG TYPE : OUT" } [1]=> array(4) { [0]=> string(2) "AM" [1]=> string(2) "PM" [2]=> string(2) "PM" [3]=> string(2) "PM" } [2]=> array(4) { [0]=> string(2) "IN" [1]=> string(3) "OUT" [2]=> string(2) "IN" [3]=> string(3) "OUT" } }
*/
foreach($matches[0] as $row){
preg_match("%[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2} (AM|PM)%", $row, $logTime);
//var_dump($logTime);
//OUTPUT array(2) { [0]=> string(10) "9:23:00 AM" [1]=> string(2) "AM" } array(2) { [0]=> string(10) "1:55:00 PM" [1]=> string(2) "PM" } array(2) { [0]=> string(10) "2:18:00 PM" [1]=> string(2) "PM" } array(2) { [0]=> string(10) "6:45:00 PM" [1]=> string(2) "PM" }
$logTime = $logTime[0];
preg_match("%(IN|OUT)%",$row, $inOut);
var_dump($inOut);
//OUTPUT array(2) { [0]=> string(2) "IN" [1]=> string(2) "IN" } array(2) { [0]=> string(3) "OUT" [1]=> string(3) "OUT" } array(2) { [0]=> string(2) "IN" [1]=> string(2) "IN" } array(2) { [0]=> string(3) "OUT" [1]=> string(3) "OUT" }
$inOut = $inOut[0];
}
I would recommend making some edits to the regex's, as I just copy and pasted the spaces. [\s]{1,} can be used in place of the crazy spaces :P
You can use
$file = file('filename.txt');
It will return the array with each element containing each line.