So, in short I have an issue I am facing where a bug in some code caused records to not be inserted into a database even though the UI told it that it was submitted (stupid checking on my part).
One thing we do though is log all the errors that are returned by the database so we can see any time a record isn't inserted and the reason why.
With this, I have all 7,200 records that need to be re-inserted into the database now that the issue has been fixed in the stored procedure.
This is how we stored the parameters that were being sent over:
xml=<data><optional><Account>1551573750449311384</Account></optional></data>, submitter=Q10004370, target=Q10224247, escalationType=aal, escalationReason=253, feedback= , preventable=1
I am going to loop over all of this data in my error log and try and prepare all of the data to re-insert back into the table. My issue is though that the string could contain less or more data; it's dynamic.
I need a way where I can search for the specific parts of the string such as xml or target.
That will allow me to set up all the data with the fields they need to be re-inserted into.
I first started with PHP's explode on the commas but realized that things are never in the same order. I then was going to try and use strpos to get the position and then get the value but had trouble doing so.
How can I go about getting the values (piece that precedes the = sign and is before the comma?
End Result is to be able to get each of the variables I need from this string so I can pass them to an insert statement to put them back into the database.
Update: While this is working, my issue now is that there could be commas in the feedback= section and its causing issues with the array.
$array = Array();
// Loop over each one of the records we are going to be working with
foreach($data->data as $p){
// Create an array of all the params
$pieces = explode(", ", rtrim($p->params, ", "));
// Debug to show all of the records we are using
/*
print '<pre>';
print_r($p);
print '</pre>';
*/
// Loop over all the params which is defined by the = sign
foreach($pieces as $item) {
// Put the values of each of the results into an array
$result[] = explode("=", trim($item));
}
// Loop over all of the results in the array
foreach($result as $item) {
// Store the param name as the key in our end result
$end[trim($item[0])] = $item[1];
}
// Push the final arrays into the results array
array_filter($end);
array_push($array, $end);
}
// Display the end results
print "<pre>";
print_r($array);
print "</pre>";
Maybe like this?
$str = 'xml=<data><optional><Account>1551573750449311384</Account></optional></data>, submitter=Q10004370, target=Q10224247, escalationType=aal, escalationReason=253, feedback= , preventable=1';
$foo = explode(",", $str);
foreach($foo as $item) {
$result[] = explode("=", $item);
}
foreach($result as $item) {
$end[$item[0]] = $item[1] ;
}
echo "<pre>";
print_r($end);
echo "</pre>";
Live link: http://sandbox.onlinephpfunctions.com/code/37aa046be2e9df37eff015ad292cd8a794a82782
Related
I have this
$homedata = $user->getbanks();
foreach ($homedata as $data)
echo json_encode(array("replies" => array(array("message" => $data->bankname))));
I have this put the result am getting is only one array from the list. I want to get all.
If I understand your requirement correctly, you need the banknames in an array replies within a key message. For that the below code will do the job. But you can optimize the query for better performance.
$homedata = $user->getbanks();
$banks['replies'] = [];
foreach ($homedata as $data) {
$banks['replies'][]['message'] = $data->bankname;
}
print_r(json_encode($banks)); exit;
Further, you were only getting the first content because you are overriding the previous content when you iterate using foreach.
I'm trying to echo a simple json_encoded file.
<?php
$allMessages = file_get_contents("chatmessages.txt");
$allMessagesArr = explode(PHP_EOL, $allMessages);
$newObj = [];
var_dump($allMessagesArr);
foreach ($allMessagesArr as $thisLine) {
// echo($thisLine . "\n");
if (empty($thisLine) ) {
} else {
$thisLineArr = explode("|", $thisLine);
$newObj[trim($thisLineArr[0])] = trim($thisLineArr[1]);
// echo("here comes another one ".$thisLineArr[0] . " : ". $thisLineArr[1]."\n");
}
}
$newObjForFront = json_encode($newObj);
echo($newObjForFront);
chatmessages.txt looks like this
bob|hello
jimmy|second try incoming again
sam|third try
bob|oh damn
I've echoed each individual line within the loop and the fourth element appears. However, when I echo $newObjForFront, it's missing the last element. Any ideas why?
When you create your final array $newObj in
$newObj[trim($thisLineArr[0])] = trim($thisLineArr[1]);
Your using the name as the index to the array. As array indexes have to be unique, this means in fact the last entry overwrites the first one, so your actual output is...
{"bob":"oh damn","jimmy":"second try incoming again","sam":"third try"}
So it is in fact the first message that is missing.
Edit:
If you wanted to just have all of the messages, then you could store them using
$newObj[] = [ "user"=> trim($thisLineArr[0]), "msg" =>trim($thisLineArr[1])];
Which would give you the output as...
[{"user":"bob","msg":"hello"},{"user":"jimmy","msg":"second try incoming again"},{"user":"sam","msg":"third try"},{"user":"bob","msg":"oh damn"}]
$newObj[trim($thisLineArr[0])] = trim($thisLineArr[1]); this line will replace value with the last message of any username. if any username have multiple messages then only last message will be stored in the array.
By creating multidimensional you can store multiple messages with the same username. Check below code that may help you
$newObj[][trim($thisLineArr[0])] = trim($thisLineArr[1]);
Im usin cURL to crabb some data from webpage.
But as the data is array based, but the size changes and varies.
Then i need to search for parts of string and want to get everyhting after the
part til next comma.
{"id":2988001,"teatiseNr":"50000099027","mkood":74,
Now here is the string.
I would only like to have everything after {"id":
til the first comma.
So my output would be 2988001
Why i need the search criteria is because some times there are more variables and that messes up the order.
Right now im using simple
$pieces = explode(",", $page);
And then just delete the rest with
str_replace('{"id":','',$pieces[0]);
There must be more elegant way to make this work.
this is a json string, so you can simply do:
$data = json_decode($string);
echo $data->id;
If it is array based then alistaircol, matei, and neil are right you should use something like
$data = json_decode($page);
$id = $data->id
Let's say for some reason the response actually not JSON and the order of the item with id is variable then something like this could work too
$no_braces = str_ireplace('{','',$page);
$no_quotes = str_ireplace('"','',$no_braces);
$items = explode(",",$no_quotes);
function getID($items){
foreach($items as $item){
$parts = explode($item, ':');
$key = $parts[0];
if($key === 'id'){
return $parts[1];
}
}
return null;
}
I don't have enough knowledge about this criteria:
I want to loop inside the for each loop to get all values in a particular column.
For example: I got the values from DB through get_result and store the result in $results.
After that use:
for each($results as $result)
❴
$output = $result->message
❵
Where message is a column in DB.
I want to loop over all the messages instead of storing last one by replacing.
Can you please give me suggestions on how to loop inside for each?
Try this:
$output[] = $result ->message;
Now $output will contain all messages on index 0, 1, 2 ...
You are facing the issue because:
$output=$result ->message;
the above line is present inside the loop, and each new iteration onerride the old value.
Well if you just looking for foreach inside foreach then you can try the following.
<?php
foreach($results as $result){
$output=$result->message;
foreach($output as $messages){
echo $messages;
}
}
?>
You don't need to put the message into another variable. You can do whatever you need to do inside the loop. For example, if you are displaying the messages, you can get it done inside the loop:
foreach ($results AS $result) {
echo $results->message . "<br>";
}
I need to get all the elements from a textarea in a HTML form and insert them into the MySQL database using PHP. I managed to get them into an array and also find the number of elements in the array as well. However when I try to execute it in a while loop it continues displaying the word "execution" (inside the loop) over a 1000 times in the page.
I cannot figure out what would be the issue, because the while loop is the only applicable one for this instance
$sent = $_REQUEST['EmpEmergencyNumbers'];
$data_array = explode("\n", $sent);
print_r($data_array);
$array_length = count($data_array);
echo $array_length;
while(count($data_array)){
echo "execution "; // This would be replaced by the SQL insert statement
}
you should use
foreach($data_array as $array)
{
//sql
}
When you access the submitted data in your php, it will be available in either $_GET or $_POST arrays, depending upon the method(GET/POST) in which you have submitted it. Avoid using the $_REQUEST array. Instead use, $_GET / $_POST (depending upon the method used).
To loop through each element in an array, you could use a foreach loop.
Example:
//...
foreach($data_array as $d)
{
// now $d will contain the array element
echo $d; // use $d to insert it into the db or do something
}
Use foreach for the array or decrement the count, your while loop
is a infinite loop if count is >0