Hi i have one situation and i dont know what exactly i need to do.
This is a multiple file upload so im doing this
$files = $_POST["files-temp"];
this return ( iten1.jpg;iten2.jpg;iten3.jpg;) there is a semicolon on last iten
then i did
$array = preg_split('/;/',$files);
then i got
Array ( [0] => iten1.jpg [1] => iten2.jpg [2] => iten3.jpg [3] => )
So there is a iten 4 that not exists, so i need to find a better way to do this then count and execut the query to save on mysql.
thanks for any help.
If $files contains a string and want to remove that last extra array location:
Try:
$files = 'iten1.jpg;iten2.jpg;iten3.jpg;';
$result = explode(";", rtrim($files,';'));
print_r( $result );
Test Here
Related
This question already has answers here:
How to extract data from csv file in PHP
(13 answers)
Closed 1 year ago.
Apologies if this question is close to others. I have tried every solution to accomplish something simple with nothing but failure. :-(
I want the keys from array one to be assigned as keys to array two.
$demos_keys = array_keys($demos);
//$c = array_combine($demos_keys, $csvdata); produces "FALSE"
//$c = $demos_keys + $csvdata; simply adds the arrays but doesn't assign keys
So then I tried to loop through each element to assign the keys manually - to no avail!
foreach ($csvdata as $row){
for($i = 0; $i<count($demo_keys); $i++) {
$csvdata[$demo_keys[$i]]=$row[$i];
}
}
demos_keys:
lastname":"lastname","email":"email","d1":"phone","d2":"status"
csvdata:
"Dryer,fdryer#email.com,Backfield,North\r","Harris,fharris#email.com,Corp,South\r",etc.
I feel the csvdata array is wonky somehow. Every thing say it is an array with about 1000 rows, but the carriage return at the end of the last element is troubling me. I thought I'd deal with it later.
What else can I try!? Thank you all for any contributions!
It looks like each row of your CSV data has not been parsed into separate variables (are you reading it from a file using fgets or file instead of fgetcsv?). So you need to split it before you can combine it with the keys from $demos_keys. Something like this should work:
$demos_keys = array("lastname","email","d1","d2");
$csvdata = array("Dryer,fdryer#email.com,Backfield,North\r","Harris,fharris#email.com,Corp,South\r");
$result = array();
foreach ($csvdata as $row) {
$data = explode(',', trim($row));
$result[] = array_combine($demos_keys, $data);
}
print_r($result);
Output:
Array
(
[0] => Array
(
[lastname] => Dryer
[email] => fdryer#email.com
[d1] => Backfield
[d2] => North
)
[1] => Array
(
[lastname] => Harris
[email] => fharris#email.com
[d1] => Corp
[d2] => South
)
)
Demo on 3v4l.org
Can i make multidimensionalarrry to assosiative array, Right now i am getting following result
Array
(
[0] => Array
(
[id] => 1
[minimum_marks] => 55
[maximum_marks] => 65
)
[1] => Array
(
[id] => 2
[minimum_marks] => 44
[maximum_marks] => 70
}
)
I just want to put all values in single, i want result like following array
Array
(
[id] => 1
[minimum_marks] => 55
[maximum_marks] => 65
)
Array
(
[id] => 2
[minimum_marks] => 44
[maximum_marks] => 70
)
Here is my code,My code not showing only one record with loop (code should showing all minimum_marks and maximum_marks), where i am wrong ?
$result = $query->result_array();
$simpleArray = [];
foreach ($result as $skuArray) {
$simpleArray['minimum_marks'] = $skuArray['minimum_marks'];
$simpleArray['maximum_marks'] = $skuArray['maximum_marks'];
}
print_R($simpleArray);
I don't know why are you expecting this output. But my suggestion, if you want it really?
$simpleArray = [];
foreach ($result as $skuArray) {
$simpleArray['minimum_marks'] = $skuArray['minimum_marks'];
$simpleArray['maximum_marks'] = $skuArray['maximum_marks'];
print_R($simpleArray);
}
Print the value inside loop, so it wont push and it wont create multiple array. every time, it will overwrite. But please be sure, finally you get last array value only on the simpleArray. Hope you understood!
Let me explain with example. If you want to display the marks in table, I will suggest you to return directly like below instead of creating variable and retrieving it again.
echo '<table>
<tr><th>Min Marks</th><th>Max Marks</th></tr>';
foreach ($result as $skuArray) {
$minMarks = $skuArray['minimum_marks'];
$maxMarks = $skuArray['maximum_marks'];
echo '<tr><td>'.$minMarks.'</td><td>'.$minMarks.'</td></tr>';
}
echo '</table>';
I don't really understand what you want.
If you want to get your array in two different variables you can try this:
Use dynamic variables, the name of the variable is dynamically generated in your loop.
foreach($result as $key => $_array){
//$key is your inder of you multidimensional
$name_variable = '_array_number_'.$key; //Name of the variable
$$name_variable = $_array; //Instanciate dynamic variable
}
//You got now this two array
print_r($_array_number_0);
print_r($_array_number_1);
But please be more precise next time with what you expect and why you need this.
By the way, what happened to your code is that in the first loop you instanciate 'minimum_marks' and 'maximum_marks' in $_simple_array.
But in your second loop you overwrite the value of 'minimum_marks' and 'maximum_marks'.
I've been bashing my head against the wall for a couple of days on this, because all indications are that this SHOULD work, so I'm obviously missing something simple.
First I am using a function to grab an array of user submitted comments
function get_id_comment_info($id) {
global $connection;
$pdo = new PDO('mysql:host='.DB_SERVER.'; dbname='.DB_NAME, DB_USER, DB_PASS);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
$sql = "SELECT parks.parkid, parks.state, pcomment.parkid, pcomment.comment, pcomment.logname
FROM parks
LEFT JOIN pcomment
ON parks.parkid=pcomment.parkid
WHERE parks.id = '$id'";
$result = $pdo->query($sql);
$cominfo = $result->fetchAll();
return $cominfo;
}
Then, inside of a foreach loop which processes each park by id, I am working with the data:
foreach ($display_result as $parkrow) {
$id = $parkrow['parkid'];
$comments = get_id_comment_info($id);
$cleancom = str_replace("'", '', $comments);
print_r($cleancom);
.
.
.
}
The output for $cleancom is:
Array ( [0] => Array ( [parkid] => 462 [0] => 462 [state] => KS [1] =>
KS [2] => 462 [comment] => I have noticed some others here say don't
waste your time, but I think it's ok. Yes, it's smaller than most, but
there is fun to be had if you are an avid rider. [3] => I have noticed
some others here say don't waste your time, but I think it's ok. Yes,
it's smaller than most, but there is fun to be had if you are an avid
rider. [logname] => John32070 [4] => John32070 ) )
It does not remove the '. If I use preg_replace then the output is simply blank. I am missing something simple, but I just can't see it!
I have tested the str_replace() function and got the following results:
$myArray = array("h'i", array("hi'hi", "yo"));
print_r($myArray);
//RESULT: Array ( [0] => h'i [1] => Array ( [0] => hi'hi [1] => yo ) )
After applying the filter:
$filtered = str_replace( "'", "", $myArray);
print_r($filtered );
//RESULT: Array ( [0] => hi [1] => Array ( [0] => hi'hi [1] => yo ) )
What the previous results show is that any string values inside the top array are indeed being converted (h'i converted to hi) while any values that form part of the multidimensional array (any arrays within arrays) are not hi'hi remained the same. This seems to be how the function was created to work.
One solution is:
$cleancom = [];
foreach ($comments as $key => $value)
{
$cleancom[$key] = str_replace( "'", "", $value );
}
The reason the previous code works is because str_replace() is never being applied to a multidimensional array, while in your previous code it was. The previous code will not work however if you have something like an array within an array within another array, so if that ends up being the case in the future, I suggest you try finding a solution with callback functions.
Let me know if this worked for you.
Want to say something else, you should put the ids in an array, then use MySQL in() function, it only need to execute once, while your method will execute many times.
I am trying to build an array from entries in a MySQL database. I have connected to the database just fine, and I have a foreach loop which pulls the entries from the database based on the quantity of items like so:
$totalMarkers = count($results);
foreach($results as $result){
$gpsLats[] = $result->gpslat;
$gpsLongs[] = $result->gpslong;
}
I then need to take these entries and run them through a while loop to attempt to build my array:
$it = 0;
while ($it < $totalMarkers) {
$incr = $it++;
$myLatitudes = $gpsLats[$incr];
$myLongitudes = $gpsLongs[$incr];
$items = array($myLatitudes,$myLongitudes);
print_r($items);
}
The problem is that the output looks something like this:
Array ( [0] => 54.8607 [1] => -32.4135 )
Array ( [0] => 39.8460 [1] => -87.4166 )
Array ( [0] => 78.8403 [1] => -95.4156 )
Really what I need is for all the entries to be contained in one array statement. I have a good feeling that I am overcomplicating this, but I need a nudge in the right direction. Thanks for your time in looking into this.
You forgot the array 'append' operation:
$items[] = array($myLatitudes,$myLongitudes);
^^--- missing
Without the [], you're simply creating a two-item array and overwriting it on every loop iteration.
I've searched around and I found some similar questions asked, but none that really help me (as my PHP abilities aren't quite enough to figure it out). I'm thinking that my question will be simple enough to answer, as the similar questions I found were solved with one or two lines of code. So, here goes!
I have a bit of code that searches the contents of a given directory, and provides the files in an array. This specific directory only has .JPG image files named like this:
Shot01.jpg
Shot01_tn.jpg
so on and so forth. My array gives me the file names in a way where I can use the results directly in an tag to be displayed on a site I'm building. However, I'm having a little trouble as I want to limit my array to not return items if they contain "_tn", so I can use the thumbnail that links to the full size image. I had thought about just not having thumbnails and resizing the images to make the PHP easier for me to do, but that feels like giving up to me. So, does anyone know how I can do this? Here's the code that I have currently:
$path = 'featured/';
$newest = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS));
$array = iterator_to_array($newest);
foreach($array as $fileObject):
$filelist = str_replace("_tn", "", $fileObject->getPathname());
echo $filelist . "<br>";
endforeach;
I attempted to use a str_replace(), but I now realize that I was completely wrong. This returns my array like this:
Array
(
[0] => featured/Shot01.jpg
[1] => featured/Shot01.jpg
[2] => featured/Shot02.jpg
[3] => featured/Shot02.jpg
[4] => featured/Shot03.jpg
[5] => featured/Shot03.jpg
)
I only have 3 images (with thumbnails) currently, but I will have more, so I'm also going to want to limit the results from the array to be a random 3 results. But, if that's too much to ask, I can figure that part out on my own I believe.
So there's no confusion, I want to completely remove the items from the array if they contain "_tn", so my array would look something like this:
Array
(
[0] => featured/Shot01.jpg
[2] => featured/Shot02.jpg
[4] => featured/Shot03.jpg
)
Thanks to anyone who can help!
<?php
function filtertn($var)
{
return(!strpos($var,'_tn'));
}
$array = Array(
[0] => featured/Shot01.jpg
[1] => featured/Shot01_tn.jpg
[2] => featured/Shot02.jpg
[3] => featured/Shot02_tn.jpg
[4] => featured/Shot03.jpg
[5] => featured/Shot03_tn.jpg
);
$filesarray=array_filter($array, "filtertn");
print_r($filesarray);
?>
Just use stripos() function to check if filename contains _tn string. If not, add to array.
Use this
<?php
$array = Array(
[0] => featured/Shot01.jpg
[1] => featured/Shot01_tn.jpg
[2] => featured/Shot02.jpg
[3] => featured/Shot02_tn.jpg
[4] => featured/Shot03.jpg
[5] => featured/Shot03_tn.jpg
)
foreach($array as $k=>$filename):
if(strpos($filename,"_tn")){
unset($array[$k]);
}
endforeach;
Prnt_r($array);
//OutPut will be you new array removed all name related _tn files
$array = Array(
[0] => featured/Shot01.jpg
[2] => featured/Shot02.jpg
[4] => featured/Shot03.jpg
)
?>
I can't understand what is the problem? Is it required to add "_tn" to array? Just check "_tn" existence and don't add this element to result array.
Try strpos() to know if filename contains string "_tn" or not.. if not then add filename to array
$path = 'featured/';
$newest = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS));
$array = iterator_to_array($newest);
$filesarray = array();
foreach($array as $fileObject):
// Check - string contains "_tn" substring or not
if(!strpos($fileObject->getPathname(), "_tn")){
// Check - value already exists in array or not
if(!in_array($fileObject->getPathname(), $filesarray)){
$filesarray[] = $fileObject->getPathname();
}
}
endforeach;
print_r($filesarray);