Changing format of a string - php

Hello My question is that i will have a textarea which i want to paste the following
[{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}},{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}]
is there any way i can run a loop which allows me to manipulate the data individually so i can update this to the database. so the first time i run the loop is get this:
{"1173627548":{"methv":"dont know","q1":"-","q2":"-","q3":"U","q4":"-","comm":""}}
if possible i want to strip out the {'s and :'s and "s so i am left with the commas and the data. For example:
1173627548,methv,dont know.. etc
sorry if i am unclear with my question in any way.

$myhugejson = 'blah...';
$array = json_decode($myhugejson, true);
foreach($array as $sub) {
print_r($sub);
echo $thing = $sub[0]['methv'];
echo $second = $sub[0]['q1'];
}
In each iteration, $sub should contain your list.
All of this is assuming you're using JSON, which I think that is.
To reference i

Related

Encoding Json Correctly?

Alright, So I'm redoing my question so people can understand what I'm trying to do.
Search.php
<?php
$getItems = file_get_contents('Items.json');
if(isset($_GET['searchVal'])){
$getItems2 = json_decode($getItems, true);
$data2 = array("items" => array(array()));
foreach($getItems2['items'] as $data){
if(strpos($data['name'], $_GET['searchVal'])){
$data2 = array("items" => array(array($data)));
}
}
echo json_encode($data2,JSON_UNESCAPED_SLASHES);
} else{
echo $getItems;
}
Problem: Doesn't get all items which have that name, gets only one.
Search is done, now I have to fix somehow to get all items which match the name. How could I do that?
You have the following inside a loop:
$data2 = array(...)
...and then you reference $data2 outside the loop.
Of course, it will only contain the last entry, because that line is overwriting $data2 with new data each time the loop iterates.
If you want to keep all the records from the loop, use
$data2[] = array(...)
instead.
[EDIT]
Further guessing as to what you actually want your JSON to look like, I guess you want all the records to be in the items array?
So in that case, let's rewrite your $data2 line, as follows:
$data2['items'][] = array($data);
This will add all the data arrays to your items array in $data2. I will note that your array structure is really convoluted -- too many nested arrays, which makes it difficult to be sure I'm giving you the answer you want even now, but hopefully if it isn't exactly right, it will show you the direction you need to go.
You'll also want to have an additional line at the top of your code to initialise $data2, like this:
$data2 = array('items'=>array());
This should be somewhere at the top of the code, before $data2 is used, and outside of the loop.

Create a string from a fetch(PDO::FETCH_ASSOC)

I am trying to build a string made of the results from sql and I do not know how achieve this when the data from the db is bigger than 1.
I was able to do it when the result from the database is one.
$result = $stmt_grade->fetch(PDO::FETCH_ASSOC);
$str ="[{$result['score_access']}, {$result['score_training']},
{$result['score_expectation']}, {$result['score_total']} ]";
but when I needed to loop the fetch_assoc I was not able to assign a value to variables or directly build the string.
while ($resultcount = $stmt_count->fetch(PDO::FETCH_ASSOC)){
$resultcount['subarea'];
}
I have looked everywhere and did not find any solutions or any similar approach to find inspiration. I hope someone can help me. Thank you in advance!
The most obvious way to do this is loop through all of the responses in a while loop, and continually append to your string using the .= operator. You can tell when you run out of records because $result will be false.
I separated each record with a newline. It also looked like you wanted to count results, so I added that, too.
$str = ""; // start with an empty string
$count = 0;
while ( ($result = $stmt_grade->fetch(PDO::FETCH_ASSOC)) !== false ) {
// increment the record count
$count++;
// add a new line to the output string
$str .= "[{$result['score_access']}, {$result['score_training']},{$result['score_expectation']}, {$result['score_total']} ]\n";
}
That should do it.
All you need is to name your string properly.
And then use a proper way to create a JSON string. Which consists of two parts:
Create a array of desired structure. Or at least provide a that structure here to let us to provide you with the code.
Use json_encode().
Assuming you need a nested array like this
[[1,2,3],[1,2,3],[1,2,3]]
the code would be
$result = $stmt_grade->fetchAll(PDO::FETCH_NUM);
echo json_encode($result);
thanks for all the answers provided without you I could not made it. Finally, I achieved the desirable result as follow, probably it is not elegant but works:
$stmt_count= $user->countbyespeciality();
while ($resultcount = $stmt_count->fetch(PDO::FETCH_ASSOC)){
$prueba.= "{$resultcount['subarea']},";
$prueba2.= "{$resultcount['number']},";
}
$string=rtrim($prueba, ",");
$string2=rtrim($prueba2, ",");
$final="[{$string}]";
$final2="[{$string2}]";
The output is [something,something] [1,2,] as expected.
thanks again!

WordPress, MySQL, php - query results not acting as a string [duplicate]

This question already has answers here:
How to modify an array's values by a foreach loop?
(2 answers)
Closed 8 years ago.
This is driving me nuts. I've searched for solutions but can't figure out what's wrong.
The situation... I have an SQL query running in WordPress, as follows:
SELECT distinct guid
FROM $wpdb->posts
WHERE post_status = 'inherit'
AND guid is not null
Dead simple. It returns a single column which contains a list of all the attachment media files currently stored on the system (well, not all of them, but it'll do as an explanation).
In a WP plugin function, I run the query:
$media_library_files = $wpdb->get_col($get_all_media,0);
That returns an array (I don't want an object) with values like:
[0] => http://mysitename.com/wp-content/uploads/2013/05/thumb_littlefile_blah.jpg
Then I want to process each one so that there's just the filename left. The problem is that, when I run a str_replace or pretty much any other string function on the contents, it doesn't work. For example:
$horrid_bit = 'http://mysitename.com/wp-content/uploads/2013/05/';
foreach($media_library_files as $item) {
$item = str_replace($horrid_bit,'',$item);
}
When I print_r the array after that, there's no visible change - every line is exactly the same as it was before.
I've tried using a (string) to cast $item, I've tried defining variables to do that, then working the str_replace on them, I've tried... loads of different things.
I have a feeling I'm missing something really simple, but I just can't see it. Is it because the column is varchar in the original table? Or something else?
Any help appreciated. Thanks!
PHP is not my 'native languague', but it seems like you're not modifying the values in the array. Did you try to put the modified string items (=minus the path) in a new array and use that one?
$horrid_bit = 'http://mysitename.com/wp-content/uploads/2013/05/';
$new_array = array();
foreach($media_library_files as $item) {
$new_item = str_replace($horrid_bit,'',$item);
$new_array.push($new_item);
}
//...use the items in the $new_array
Also, you might wanna just read the whole path string as an array (split on '/')and take the last element to get to the file.
$horrid_bit = 'http://mysitename.com/wp-content/uploads/2013/05/';
foreach($media_library_files as $key => $value) {
$media_library_files[$key] = str_replace($horrid_bit,'', $value);
}
But as Michael pointed out if you are not doing it this way for a specific purpose using basename would be better here, so you don't have to worry about the folder changing each month/year.
foreach($media_library_files as $key => $value) {
$media_library_files[$key] = basename($value);
}
You are not actually changing the value of $item in your array, you are instead creating a new variable, which is then overwritten every time your loop iterates.
It's also a good idea to check that the array is not empty before attempting a foreach() loop on it.
Finally, I've replaced str_replace() with basename() (as suggested in the comments under your question by #MichaelBerkowski).
if(!empty($media_library_files)) : foreach($media_library_files as $item) :
$media_library_files[$item] = basename($item);
endforeach;
endif;
str_replace() can handle arrays. No need for your foreach loop.
$horrid_bit = 'http://mysitename.com/wp-content/uploads/2013/05/';
$media_library_files = str_replace( $horrid_bit,'',$media_library_files );
On the other hand, since it seems you want to remove the path and get only the filename:
foreach($media_library_files as $key => $item) {
$media_library_files[$key] = basename($item);
}
This will change all entries to the filename only. The way you have it now you will have to change the $horrid_bit every month since the uploads are organized in year/month/ folders.

Storing formatted variable into MySQL DB?

I had this working by simply passing the data from one variable to another like so:
$CalcsSets = $DisplayCalcs;
without the need to use the loop inside the first if() statement and it inserted the data without quotes but all of a sudden it's stopped working and I'm not sure why (it only started showing last integer), so I went with the more complex code trying to get it to work again as shown below.
Here's the complex code I'm working with:
for($i=1; $i<=$CalcSets; $i++){
$calculations = PerformCalc($min, $highest, $OperatorType);
echo 'Calculations performed for '.$SetText[$i];
foreach ($calculations as $key => $DisplayCalcs) {
echo $SetCalc[] = $DisplayCalcs.', '; //stores calculations with ',' in
//array.
}
if($CalcSets == 1){
for($i=0;$i<$CalcSets;$i++){
$SetResults = $SetCalc[$i];
echo '<strong>'.(string)$SetResults.'</strong>';
}
DB_Insert($SetResults);
}
What it's supposed to do is insert values in the following format (1,2,3,4,5,) into the database in a VARCHAR row but now all it shows is the last integer with no comma. I originally wanted to just store the integers and not a comma but I couldn't get it to display on the page with commas after each integer so I went this route as mentioned earlier.
I realize I'm probably going about this the wrong way, but if any of you know a much easier, and shorter, way to do what I want, I'd be extremely appreciative of the help.
Reason I'm doing it this way, is because on the results page, it needs to show in the format mentioned above.
FYI, I did check the DB row and it is still set to VARCHAR with a length of 10 at the moment.
UPDATE TO MAKE INTENTIONS MORE CLEAR
Ok, I'm going to go back to square one and try to make my intention as clear as possible. I've been rewriting this code snippet more times than I care to count and my brain is all foggy lol.
array1 = array(1, 2, 3, 4, 5, 6);
foreach(array1 as $key => $data){
echo $data.',';
// will display 1,2,3,4,5,6, in browser.
}
if(is_true == 1){
INSERT ALL $data values into DB here.
}
That's what I'm trying to accomplish in it's simplest form, I'm just have extreme difficulty achieving my goal.
Second Update - Topic Solved
Apparently, the DB field had to be set to Text rather than VarChar. I guess we learn something new everyday.
Again, thanks everyone for all of your help. It was greatly appreciated!
I'm sorry but I couldn't make much sense from the original code but focusing only on the last IF and the containing LOOP, I think the problem is with the assignment statement:
$SetResults = $SetCalc[$i];
It should instead use .= for concatenation. Here is how it should look:
if($CalcSets == 1){
for($i=0;$i<$CalcSets;$i++){
$SetResults .= $SetCalc[$i];
echo '<strong>'.(string)$SetResults.'</strong>';
}
DB_Insert($SetResults);
}
Hope it works!
I completely agree with the solution from #KemalFadillah for using the implode() method. From your code snippet, I understand that $calculations is the array that stores the main values, i.e. Array(1, 2, 3, 4, 5). So you can do:
$calculations = PerformCalc($min, $highest, $OperatorType);
$s = implode (', ', $calculations);
DB_Insert($s);
I hope that makes sense?
You are executing the last for loop only if $calcSets == 1 and have an $i<$calcSets condition
How about doing it like this
$SetCalc = "";
foreach ($calculations as $key => $DisplayCalcs) {
 echo $SetCalc .= $DisplayCalcs.', ';
}
DB_Insert("(".$SetCalc.")");
You're looking for the implode() function to format the numbers.
$formatted = implode(',', $calculations); // Produce 1,2,3,4,etc...
http://php.net/manual/en/function.implode.php

PHP, problem with str_replace while reading from array

i am new to php, and i am trying to do a script that reads an CSV file(file1.csv) and compare the words in the file with words in a html file (file2.html), if word in file2.html match with the key part in file1.csv it should change the file2.html contents with the value of the key matched ..
what i have done so far is this :
$glossArray = array();
$file_handle = fopen("file1.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 10000,';');
$glossArray[$line_of_text[0]] = $line_of_text[1];
$counter++;
}
fclose($file_handle);
$file = file_get_contents("file2.html");
foreach($glossArray as $key => $value){
$results = str_replace($key," means ".$value ,$file);
}
echo $results;
i think that my problem occurs when i try to iterate and change values .. because what i see is only the contents of file2.html unchanged
any help would be appreciated
thank you in advance
Nader
P.s. i edited the old code with the new one after your valuable advise .. now it's like this .. but still doesnt work.
Update: changing the foreach with :
$results = str_replace(array_keys($glossArray), "means ".array_values($glossArray), $file);
solved the problem .. but another one comes up: now every time it replaces a string it adds the word 'Array' ahead of it.
You're passing the entire $glossArray in to str_replace each time. You're also passing the initial file contents in each time you do str_replace, so at most you'd see one replacement. I think you want to change to something like this:
$results = $file;
foreach($glossArray as $index=>$value)
{
$results = str_replace($index,$value ,$results);
}
Since str_replace allows arrays for the first two parameters (as another user mentions) you could also do something like this instead of a loop:
$results = str_replace(array_keys($glossArray), array_values($glossArray), $file);
Yes, the problem is in your second foreach. It should read like this:
foreach($glossArray as $key => $value){
$results = str_replace($key,$value ,$file);
}
You forgot the key, so it's replacing every instance of every value in $glossArray with the $value. Good luck with that!
Why are you opening file2.html for reading and writing, then grabbing the contents of it?
(BTW - this is going to go horribly wrong on a system with strict locking)
foreach($glossArray as $value)
{
$results = str_replace($glossArray,$value ,$file);
I think this should be
foreach($glossArray as $old=>$new)
{
$results = str_replace($old, $new, $file);
Although it would be a lot more efficient to load the pairs from the glossary into 2 seperate numbered arrays, then just call str_replace once.
Your first parameter for str_replace should not be $glossArray as that's an array and not the string to replace.
I assume that your CSV-file contains something like "SEARCH;REPLACE"? In that case, your foreach should look like this: foreach ($glossArray as $searchString => $value).
Then try
$file = str_replace($searchString, $value ,$file);
instead of
$results = str_replace($searchString, $value ,$file);
because right now you're overwriting $results again and again with every str_replace ... echo $file when you're done.
BTW: What's $counter doing?
The solution to your new problem (which should really be it's own question, not an edit of the existing one) is that array_values returns an array, and when you concatenate an array with a string, php inserts 'Array' instead of the value.
$results = str_replace(array_keys($glossArray), "means ".array_values($glossArray), $file);
is incorrect. You should do this instead:
$vals = array_values($glossArray);
foreach($vals as $k=>$v)$vals[$k] = 'means '.$v;
$results = str_replace(array_keys($glossArray), $vals, $file);
Notice that the values of glossArray are extracted, and each value concatenated with your string - if you just try and concatenate the string with the array, you'll get a string, not an aray.

Categories