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

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.

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.

Assign foreach variables

I've tried, believe me I've tried to figure this out but for the best part of the day it has beaten me so I have to ask this question:
I have a list ($list) of 100 words which I have put into an array:
foreach ($tag_array as $key => $names ) {
Each of these names I want to be a variable which I can use to assign some html for output within a html eg:
$arrayitem6 = 'whatever';
print $arrayitem6;
The reason I want to do this is because the 100 items in the list actually turns into 400 items in a html page which I would have to manually write out into a huge long repeating block of html. I want to create a single block of html/code using the array list and foreach.
I hope I've made myself understood. I'm sure it's a straight forward bit of coding but as a novice I cannot fathom.
thanks in advance for any help
I have searched the internet and googled but I can't locate an answer. I'll keep looking.
thanks
Try following
<?php
foreach ($tag_array as $key => $names ) {
${"arrayitem$key"} = $names;
}
echo $arrayitem0;
?>
You can access variable as $arrayitem0, $arrayitem0 and so on depending upon key ($key) of your $tag_array
I think this is what you are looking for.
<?php
foreach ($tag_array as $key => $names ) {
$."arrayitem".$key = $names;
}
echo $arrayitem6;
?>
you can access variable as $arrayitem0 ,$arrayitem1...till 99

How do I loop through and change values in this PHP object?

Here is a fairly big object dumped using print_r.
https://docs.google.com/document/d/175RLhWlMQcyhGR6ffGSsoJGS3RyloEqo4EEHCL2H2vg/edit?usp=sharing
I am trying to change the values of the uploaded_files.
Towards the end of that object you'll see something like
[uploaded_files] => Array
(
[attachment] => /home2/magician/public_html/development/testing/wp-content/uploads/wpcf7_uploads/Central-Coast-Montessori-logo.jpg
[attachment2] => /home2/magician/public_html/development/testing/wp-content/uploads/wpcf7_uploads/Andrew.jpg )
My code
// move the attachments to wpcf7ev temp folder
foreach ($cf7ev_object['uploaded_files'] as $key => $uploaded_file_path) {
$new_filepath = WPCF7EV_UPLOADS_DIR . '/' . basename($uploaded_file_path);
wpcf7ev_debug("New file path is {$new_filepath}");
rename($uploaded_file_path, $new_filepath);
wpcf7ev_debug("'{$key}'is the KEY for {$uploaded_file_path}");
wpcf7ev_debug($cf7ev_object['uploaded_files']);
$cf7ev_object['uploaded_files'][$key] = $new_filepath; // this is not updating
}
To loop through it I have been using
foreach ($cf7ev_object->uploaded_files as $key => $uploaded_file_path) {
and this has worked.
But shouldn't it be
foreach ($cf7ev_object['uploaded_files'] as $key => $uploaded_file_path) {
? As '->' is for accessing methods?
And specifically I want to update the values of those uploaded_files, so to do that I need to do
$cf7ev_object['uploaded_files'][$key] = $new_filepath; // this is not updating
? But this doesn't seem to be working.
I think I need to be clear on how to access values in an object.
Thanks.
First of all, regarding the single arrow "->" that is how you reference an objects values. But I won't get into that. Since you say it works, $cf7ev_object is obviously an object.
You say you want to "access the values in the object".
var_dump($cf7ev_object);
This will spit out what is in that object. I gather you are a bit of a newbie, so I will try to help you out best I can with the limited data you provided (you may want to expand your question.
Looping is not a one-shot deal. You can have nested loops and nested loops inside of those. However, it is a resource hog if you're not careful. Here is an exercise that might help you.
$new_array = array();
foreach($cf7ev_object->uploaded_files as $key => $value) {
$new_value = $value;//do something to the $value here
$new_array[$key] = $new_value;
}
//take a look at your work now:
print_r($new_array);
I hope this helps. Note: your google doc is restricted, public can't see it.. And your question is too vague. Let me know if I can help more.
If you want to change the object array values instantly you just set it equal to the above loop result:
$cf7ev_object->uploaded_files = $new_array;

Changing format of a string

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

Problem with associative arrays

I have always sucked at complex arrays there must be something in my brain preventing me from ever understanding them. I will try to make this example really simple so we will not go off topic. I use this code to use numbers to represent each file name:
$mod_nums = array('1' => $input_zip_path . '01_mod_1.0.2.zip',
'2' => $input_zip_path . '02_mod_1.0.1.zip',
);
So when I use $mod_nums['01'] it will display the path to that file. I have an array from the script that put these $mod_nums values into an array like so:
$files_to_zip = array(
$mod_nums['1'],
$mod_nums['2']
);
That worked fine. Now I wanted to add a $_POST value so that I can enter numbers like 1,2 and other numbers that I add to the $mod_nums array later like 1,3,6,12 for example. So I used an explode for those posted values:
$explode_mods = explode(",", trim($_POST['mods']));
Now for the big question that is racking my brain and spent hours on and cannot get it to work.... I need for $files_to_zip to still be in an array and display the posted values of $mod_nums. So it would be like:
$files_to_zip = array( HAVE $_POSTED VALUES IN HERE );
I hope that makes sense. I need $files_to_zip to remain in array format, grab the file path to the zip files from the $mod_nums array, and display it all correctly so it would dynamically output:
$files_to_zip = array('01_mod_1.0.2.zip', '02_mod_1.0.1.zip');
so posted numbers will appear in an array format for the $files_to_zip variable. Make sense? In short I need an array to have dynamic values. Thanks :)
EDIT
Phew I figured it out myself from memory when I worked on something similar many years ago. This looks tough but it isn't. I had to use a foreach and assign the variable into an array like so:
$blah = array();
foreach ($explode_mods as $value)
{
$blah[] = $mod_nums[$value];
}
then I just assigned $files_to_zip to $blah:
$files_to_zip = $blah;
works perfectly :) I just forgot how to dynamically assign values into an array.
// filenames array
$mod_nums = array('1' => $input_zip_path . '01_mod_1.0.2.zip',
'2' => $input_zip_path . '02_mod_1.0.1.zip',
);
// mod_num keys
$explode_mods = explode(',', trim($_POST['mods']));
// array to hold filenames
$files_to_zip = array();
// loop over all the mod_num keys submitted via POST
foreach($explode_mods as $key){
// save the filename to the corresponding array
$files_to_zip[] = $mod_nums[$key];
}
maybe i havn't understood you right, but won't this just be a simple foreach-loop to add the entrys to $files_to_zip like this:
$explode_mods = explode(",", trim($_POST['mods']));
foreach($explode_mods as $k){
$files_to_zip[] = $mod_nums[$k];
}

Categories