Remove string from an stdClass object in php - php

I have an array called $field->selectoptions[1]
print_r($field->selectoptions[1]) gives these results:
stdClass Object ( [voption] => clabels [clabel] => Data Inizio
[values] => Qualsiasi Data 1 Luglio 2016 12 Settembre 2016 14 Novembre
2016 [slabel] => Data Inizio )
I need to remove from [values] all invalid dates, in this case "1 Luglio 2016" (July 1st 2016) because the date has passed
I tried using unset but that's appears to be a single string.
I don't think a str_replace would work either...
Any idea?

Related

Laravel-Excel 2, get the year and month from "date" in Carbon format

In Laravel-Excel 2, I'm reading a file like this:
The code to read it is this:
$my_file ='some/path/to/my_file.xls';
$data = Excel::selectSheetsByIndex(0)->load($my_file, function($reader) {})->get()->toArray();
This it the output for dd($data[0]);, considering that datais an array:
I need to get the year (2005) and month (11) from "date". "date" is inside "fecha" and it is in Carbon format. How can I get it? I've been having a lot of problems reading that array-object thing. I thought that $data[0]["fecha"]->date would do the trick but, instead of that it works with:
$data[0]["fecha"].["date"]
But I'm having some errors in some versions of php with "Array to string conversion", but in my php it doesn't show the error, so how should I get that year and month? I don't get it.
This is the output of print_r($data[0]);die();:
Array (
[fecha] => Carbon\Carbon Object (
[date] => 2005-11-01 00:00:00.000000 [timezone_type] => 3 [timezone] => America/Santiago
)
[hora] =>
[bloquefr] => N
[dia] => 1
[activo_defecto] => 118.209
[reactivo_defecto] => 0
[empresa] => Luz Osorno
[barra_internal_name] => La Union 13.8
[barra_cen_name] => La Union 13.8
[barra_cne_name] => L.UNION_______013
[barra_cen_name_2] => La Union 1 023
[tipo_barra] => SPD
)
EDIT: the output of print_r($data[0]["fecha"].["date"]);die(); is
2005-11-01 00:00:00Array
I don't know what it means that...
try
$data[0]["fecha"]->formatLocalized('Y'); // 2005
$data[0]["fecha"]->formatLocalized('m'); // 11
EDIT: the output of print_r($data[0]["fecha"].["date"]);die(); is
2005-11-01 00:00:00Array
because you are concatenating $data[0]["fecha"] and ["date"] with the operator '.' and printing it. Internally, is interpreted as:
$data[0]["fecha"]->toString.["date"]->toString
Try to call directly from Carbon object:
$str = $data[0]["fecha"]->format('Y m');

Getting data from a json file with arrays

I'm having troubles to get specific data from a json file using the built-in php functions.
Let me show you some code :
Json File :
{"votes": [ { "date":"November 3rd, 2017 10:08 PM EST", "timestamp":1509743288, "nickname":"Th3ProHack3R", "claimed":"0" }, { "date":"November 3rd, 2017 10:06 PM EST", "timestamp":1509743160, "nickname":"TheKing", "claimed":"0" }, { "date":"November 3rd, 2017 09:45 PM EST", "timestamp":1509741902, "nickname":"some0ne", "claimed":"0" } ] }
My php code :
$json= file_get_contents("myfile.json");
$data = json_decode($json, true);
$voter1 = $data['votes']->nickname;
echo $firstvoter;
I had this code working on a very basic json code without arrays. But something is wrong here because I can't get the nicknames of the voters.
I'm just a little bit confused, so what I wanna do is picking up the nicknames of the voters and then I'll put them on a table using html.
I hope I get a detailed answer so I can understand some of the confusing stuff.
you need to get array to json object. hear "votes" is json object so $data['votes'][0] is return first array see code...
<?php
$json= file_get_contents("myfile.json");
$data = json_decode($json, true);
$voter1 = $data['votes'][0];
$voter2 =$data['votes'][1];
print_r( $voter1);
echo "<br>".$voter1["nickname"];
echo "<br>".$voter2["nickname"];
?>
After converting into json Decode you array make look like this,
Array
(
[votes] => Array
(
[0] => Array
(
[date] => November 3rd, 2017 10:08 PM EST
[timestamp] => 1509743288
[nickname] => Th3ProHack3R
[claimed] => 0
)
[1] => Array
(
[date] => November 3rd, 2017 10:06 PM EST
[timestamp] => 1509743160
[nickname] => TheKing
[claimed] => 0
)
[2] => Array
(
[date] => November 3rd, 2017 09:45 PM EST
[timestamp] => 1509741902
[nickname] => some0ne
[claimed] => 0
)
)
)
In this you need the nickname:
foreach ($jsonData['votes'] as $key => $value) {
echo "Nickname : ". $value['nickname']."<br/>";
}

PHP Arrays duplicating?

I am trying to code a cron job so if a code in the database and is unused and older then 72 hours it drops the row in the database.
The problem I am having however is that when I am trying to get the array data in a row, so I can run an 'If statement' and then the drop command, when printing the array I get duplicates like as follows
33520891520891do not usedo not use----aaron hattonaaron hattonSunday 8th of September 2013 12:46:20 PMSunday 8th of September 2013 12:46:20 PMUnusedUnused--
My code is as follows
// Set variable for the time
$timenow = date('l jS \of F Y h:i:s A');
// Start Expired password check and drop function
function cronexec_expired ($timenow) {
include('../../config.php');
// Open up a new MySQLi connection to the MySQL database
mysql_connect($dbHost, $dbUsername, $dbPassword);
mysql_select_db($dbTable);
// Query to check the status of the code input
$expiry_check = "SELECT * FROM code_log WHERE status='Unused'";
// Run the query
$expiry_checkexec = mysql_query($expiry_check);
while($expiry_possibles = mysql_fetch_array($expiry_checkexec)) {
foreach ($expiry_possibles as $expiry_possible) {
print_r ($expiry_possible);
};
}
}
// Start Redeemed Password check and drop function
// Execute Functions
cronexec_expired ($timenow);
Any help would be really appreciated!
Edit
When removing the 'foreach' and running the following:
print_r ($expiry_possibles);
I get the following
Array ( [0] => 3 [id] => 3 [1] => 520891 [code] => 520891 [2] => do not use [refid] => do not use [3] => - [hostname] => - [4] => - [userip] => - [5] => aaron hatton [creater] => aaron hatton [6] => Sunday 8th of September 2013 12:46:20 PM [timecreated] => Sunday 8th of September 2013 12:46:20 PM [7] => Unused [status] => Unused [8] => - [timeredeemed] => - )
Am I doing something wrong?
if you mean numeric index in your array output. use mysql_fetch_assoc() instead of mysql_fetch_array()
mysql_fetch_array() essentially returns two arrays one with numeric index, one with associative string index.

Two idential datetimes; one shows 12 hour the other 24 hour

I have a form with two datetime fields. The user inputs the date (yyyy-mm-dd) and time (3 boxes; hour, minute, am/pm).
For some reason, the first one isn't getting saved as a 24 hour time.
The following data is the result of entering:
2011-1-1
4:30 PM
I am using strtotime() to convert a string to a datetime format.
$dateOccured = date('Y-m-d H:i:s', strtotime($dateOccurred));
$dateResolved = date('Y-m-d H:i:s', strtotime($dateResolved));
If I use print_r() to look at the results of this, it is showing correctly.
Date Occurred:
[year] => 2011
[month] => 1
[day] => 1
[hour] => 16
[minute] => 30
[second] => 0
[fraction] => 0
[warning_count] => 0
Date Resolved
[year] => 2011
[month] => 1
[day] => 1
[hour] => 16
[minute] => 30
[second] => 0
[fraction] => 0
[warning_count] => 0
Both show the correct time: 16:30 (or 4:30PM). When I look in my database, this is what is shown.
Date Occurred
2011-01-01 04:30:00
Date Resolved
2011-01-01 16:30:00
I know it's a problem with the dateOccurred variable because if I replace it with dateResolved in my query, it gets inserted correctly. What I can't figure out is where the problem is? What am I missing that is causing this?
Thank you.
If it was the database, wouldn't replacing the dateOccurred variable with dateResolved in the query not matter?
Here is the INSERT query
"INSERT INTO
incidents (
incidentNumber, date, itFunction, issue, severity,
owner, dateOccurred, dateResolved, locationsImpacted, businessImpact,
rcaRequired, rcaReceived, rootCause, notes)
VALUES (
'{$incidentNumber}', '{$date}', '{$itFunction}', '{$issue}', '{$severity}',
'{$owner}', '{$dateOccurred}', '{$dateResolved}', '{$locationsImpacted}', '{$businessImpact}',
'{$rcaRequired}', '{$rcaReceived}', '{$rootCause}', '{$notes}')"
They are both datetime fields.
Found the problem...typos! I've been bashing my head against the wall for an hour trying to figure this out! $dateOccured (single R...rrrrrr)! Put this one in the embarrassing column.
I learned that error reporting can be made more useful by using
error_reporting(E_ALL | E_NOTICE)
Thanks to Chronial for that.

Identify date-related text in a longer message

I'm currently writing a script that would extract all the dates from a message and convert them to timestamps. PHP's strtotime (similar to Unix's date -c 'some date') would be perfect for this, as it recognizes all kinds of dates, such as:
5pm today
2010-11-15 16:30
Thursday 8:00
However, I'm having trouble finding those dates in the first place. For example, in the following string,
I'll be there for dinner tomorrow at 9:00pm
I need to isolate "tomorrow at 9:00pm", as that's the part that strtotime recognizes.
Is there a regular expression or something similar that would return me all dates that can be parsed by strtotime?
The only thing I can think of is date_parse. A regular expression that matches any format accepted by strtotime would be huge.
An example of date_parse:
$str = "I'll be there for dinner tomorrow at 9:00pm";
$parsed = date_parse($str);
print_r($parsed);
It would output something like this (I removed the unimportant parts from it to make it the result lighter):
Array
(
[year] =>
[month] =>
[day] =>
[hour] => 21 // 9:00pm
[minute] => 0 // 9:00pm
[second] => 0 // 9:00pm
[fraction] => 0
[warning_count] => 1
[is_localtime] => 1
[zone_type] => 2
[zone] => -540
[is_dst] =>
[tz_abbr] => I
[relative] => Array
(
[year] => 0
[month] => 0
[day] => 1 // tomorrow (would be -1 for yesterday, etc.)
[hour] => 0
[minute] => 0
[second] => 0
)
)
Whether this works for you depends primarily on what your input looks like. If you have more than one instance of a date in your input string, it will not work as expected.
This might not be totally efficient, but should work for any date string that consists of up to 5 words in length. I would write the function, but I think you'll get the idea with the comments below...
$words = explode(' ',$original_string);
// Use the array_chunk() function break up this array into 1-word,
// 2-word, 3-word, and 4-word long substrings of the original string
// Reform them back into strings and pass each one through strtodate()

Categories