PHP - Getting String From Looped Array
Hello,
I'm going to be sending emails to users from a community calendar showing events for the day or a time frame specified elsewhere. The problem I'm having is turning results of DB query into a string when there are multiple results for the day. It works just fine with single results. I understand why it doesn't work but can't figure out how to solve the problem. Don't worry about the $eventdate as that comes from the same array as the $event_id used to call the array shown below. I tried foreach and implode but couldn't get it working so I'm starting over and asking for your guidance on how is the best way to pull this off. Thanks for your help. Code: [Select] $getevent = mysql_query("SELECT title, description from ".$conf['tbl']['events']." WHERE event_id=$event_id AND private=0"); WHILE ($gtevent = mysql_fetch_array($getevent)) { $event_title=$gtevent['title']; $event_description=$gtevent['description']; $message="<p><span style=\"font-size:24px\">$event_title</span><br />$eventdate</p><p>$event_description</p>"; } Similar TutorialsI have this function, but it doesnt work. Basically the list outputs a list of news features, and puts a line under neath each article to seperate them. However once the last article has been reached, I don't want the break to be shown. this is my code, any help would be appreciated as i am really struggling on this. Just need to determine the last item in the array, and stop the <hr split> from being output. function newsFeature(){ $event = "SELECT imgname, title, content, pkID from news ORDER BY date, time DESC LIMIT 5"; $event_page = query($event); $count = numRows($event_page); while ($row = mysql_fetch_assoc($event_page)) { $rowcount = $count; $para = substr($row['content'] , 0,100); $result .= '<article>'; $result .= '<a href="news-article.php?pkID=' . $row['pkID'] . '"><img src="uploads/thumbs/' . $row['imgname'] . '" alt="" width=116 height=83/ ></a>'; $result .= '<h2><a href="news-article.php?pkID=' . $row['pkID'] . '">' . $row['title'] . '</a></h2>'; $result .= '<p>' . $para . '...</p>'; $result .= '<p><a class="read-more" href="news-article.php?pkID=' . $row['pkID'] . '">Read more<span></span></a></p>'; $result .= '</article>'; if($row != end($row[])){ $result .= '<hr class="split">'; } } return $result; } So I'm trying to create an Array from a comma separated string containing array{s}. How can I take a string full of comma separated hex values such as : <?php $myStr = ( "00ffff", "00cccc", "009999", "007777", "004444", "001111", "01ffff", "01cccc", "019999" ); ?> & turn it into 3 separated arrays like : <?php $myNewArrs = [ Array1 ( 3 ), Array2 ( 3 ), Array3 ( 3 ), ]; ?> which REALLY looks like : <?php $myNewArrs = [ Array ( "00ffff", "00cccc", "009999" ), Array ( "007777", "004444", "001111" ), Array ( "01ffff", "01cccc", "019999" ), ]; ?>
? Thank you & have a great afternoon!
Edited May 27 by AquariaXI Hi, I want to loop out data from DB in <input> and change and update several posts at the same time. Can you give me a short example, how <input> and maybe foreach could look like? Thanks I'm trying to figure out how to add up all the $qty_total that exist into an overall total. I hope I'm not oversimplifying my example.. I have this: $qty_total = $qty_insert * $d['workshop_price']; $qty_insert loops several times and I want: $overall_total = $qty_total + qty_total + ...however many.. I cannot get this INSERT to work. Not records are being added to the sys_city_dev table. No query errors are being thrown. I am simply trying to add ALL records from all_illinois to sys_city_dev and Mid should have be add as 11 in all inserts. city_name of course will be field city_name from all_illinois. Here is my code: $query = "SELECT * FROM all_illinois"; if ($results = mysqli_query($cxn, $query)) { $row_cnt = mysqli_num_rows($results); echo $row_cnt . " Total Records in Query.<br /><br />"; if (mysqli_num_rows($results)) { while ($rows = mysqli_fetch_array($results)) { echo $rows['city_name'] . "<br />"; $mid_id = '11'; $insert_city_query = "INSERT INTO sys_city_dev (ID, Mid, cityName, forder, disdplay, cid) VALUES (' ','" . $mid_id . "','" . $rows['city_name'] . "', '', '','')"; if (!$insert_city_query) exit(mysql_error()); } } } Here is my insert table structure and 5 records dump: -- -- Table structure for table `sys_city_dev` -- CREATE TABLE IF NOT EXISTS `sys_city_dev` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `Mid` int(11) NOT NULL DEFAULT '0', `cityName` varchar(30) NOT NULL DEFAULT '', `forder` int(4) NOT NULL DEFAULT '0', `disdplay` int(4) NOT NULL DEFAULT '0', `cid` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`ID`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=113970 ; -- -- Dumping data for table `sys_city_dev` -- INSERT INTO `sys_city_dev` (`ID`, `Mid`, `cityName`, `forder`, `disdplay`, `cid`) VALUES (84010, 1, 'Dothan', 0, 0, 0), (84011, 1, 'Alabaster', 0, 0, 0), (84012, 1, 'Birmingham', 0, 0, 0), (84013, 2, 'Flagstaff', 0, 0, 0), (84014, 1, 'Auburn', 0, 0, 0); And the all_illinois dump w/ 5 records: -- -- Table structure for table `all_illinois` -- CREATE TABLE IF NOT EXISTS `all_illinois` ( `state_id` varchar(255) NOT NULL, `city_name` varchar(255) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `all_illinois` -- INSERT INTO `all_illinois` (`state_id`, `city_name`) VALUES ('135', 'Abingdon'), ('135', 'Adair'), ('135', 'Addieville'), ('135', 'Addison'), ('135', 'Adrian'); Hi all, Im really struggling to build an update multiple records form, Ive built my table which calls all data i need from the db in a looped region which works fine I just cant understand how to then input these back into the table in the correct rows, if this makes sense? Ive been reading this tutorial but Its not very informative its more of a copy and paste http://www.phpeasystep.com/mysql/10.html OK so here is what I want to do. I have a bunch of strings stored in a table. The strings are like this grandparent.parent.child. some are just parent.child What I want to do is Select all and then put them into an array. soooo x.y.z would become $Var['x']['y']['z'] and a.b would become $Var['a']['b'] It has to be dynamic because some strings are just 2 levels, and it goes all the way up to 6 levels. I have different plans for setting the variably to something but I can handle that. Any ideas? Hi all, Im so stuck on this! Cant figure out a solution... $precip_array[0] has a value of "80" in it as a string. I need to compare it to an integer. echo (int)$precip_array[0] returns a "0". Ive also tried adding a 0 but that results in the same. I did a var_dump on $precip_array[0] which returns string(17) "80" I think 17 signifies the length of the string, but I only see 2 digits when I echo this. Any help is much appreciated. Hi I need to know how to arrange this thing looking something like an array to be able to find values from it. The problem is, I don't really even know what I am dealing with here. Wonder if you could help me out. I have the following mess stored in a $messages variable: {"messages":[{"message_id":2314446,"from":"441234568790","timestamp":1280703181,"text":"first text"},{"message_id":2315147,"from":"123456789014","timestamp":1280755014,"text":"another text"}],"unread":0} and I don't know how to do the following: I need is to get only the message text from any message that matches my wanted phone number. For example: I want to get the text value from message which from is 123456789014. /Henry I want to echo the last two (or at least the last) string of an array. What is the simplest way to do so ? I need to assign unknown array keys and their values to strings. The code I am using is: Code: [Select] $cart = $_SESSION['cart']; $items = explode(',',$cart); $qty = array(); foreach ($items as $item) { $qty[$item] = $qty[$item] + 1; } print_r($qty); The keys change and are not ordered. I do not know what the key or it's value may be. So as an example, I might have: Code: [Select] Array ( [2] => 5 [4] => 8 ) or in a different scenario, I might have: Code: [Select] Array ( [1] => 6 ) What those numbers represent is a product id (the key), and the quantity (the value of the key). Can someone help me to assign these to a string? I have been reading all morning, and not making any progress. Thank you!
<?php $srs = array(); for ($section = 1; $section < 5; $section++) { for ($row = $section; $row < 10; $row++) { for ($seat = $row; $seat < 20; $seat++) { $srs[] = array( 'section_name' => $section, 'row_name' => $row, 'seat_name' => $seat); } } } output(convert_array($srs)); // Converts the array function convert_array($input) { return $input; } function output($obj) { echo "<pre>"; print_r($obj); echo "</pre>"; die; } ?>
I'm trying to convert those array number to string, add implode() to make it happen, but seem PHP didn't recognize variable in $input. Like this implode("Section: ", $input) or (Section: ", $srs). Can you help me? Thanks, Gary Edited October 16, 2019 by sigmahokiesHello, I have a string that contains a directory path much like: "/images/icons" and I want to take that string through a function and explode it into an array of directories that with add my directory structure array: images icons Then if I were to send the string "/data/documents" to the function it would append to the existing array: images icons data documents Here's the code that I've got thus far: <?php $global_structure = array(); generate_structure("./images/icons"); generate_structure("./data/documents"); function generate_structure($directory) { if(!is_dir($directory)) return false; $directory_structure = explode("/", $directory); // do something here to iterate over $global_structure and add new directories to equal to current directory path making the value an empty array. } ?> Hi all, i have this array $str = array("apple is red", "banana is yellow", "pineaple is tropical fruit", "coconut is also tropical fruit", "grape is violet"); i want to find string "coconut" inside $str and put the whole string "coconut is also tropical fruit" into variable $coconut. can i do this? i don't want to use the this code Code: [Select] <? $coconut = $str[3]; echo "$coconut"; ?> can someone help? Thank you, Best Regards Hi, I know the problem that I am having is related to the change in PHP5 about strings and arrays, however I do not understand why my script is affected. It seems like I am not trying to add more variables to an array. I do not success in order solve the problem. Help me please: // Build View Array if ($view_result!=false) { $i=0; while ($view_row =@ mysql_fetch_array($view_result)){ $i++; $view_rows[$i] = $view_row; // build view_comments array if ($viewcomments=="yes") { $sql = "SELECT * FROM blog_comments WHERE nBlogId=".$view_row["nIdCode"]." ORDER BY nIdCode DESC"; $result = mysql_query($sql,$con); if ($result!=false){ $j=0; while ($comment_row =@ mysql_fetch_array($result)){ $j++; $view_comment_rows[$i][$j] = $comment_row; } } } } } else { $problem = "2"; } // increment view counter for either the single blog being shown // or ALL blogs being shown //The problem is here if ($view_rows[1]["nIdCode"]!="" && strpos($_SERVER["PHP_SELF"],"admin.php")==false){ if ($viewmode=="single"){ $blogid = $view_rows[1]["nIdCode"]; $sql = "UPDATE blog SET nViews=nViews+1 WHERE nIdCode=".$blogid; } else { for ($i=1;$i<=count($view_rows);$i++){ $blog_array[$i] = $view_rows[$i]["nIdCode"]; } $blogids = implode(",",$blog_array); $sql = "UPDATE blog SET nViews=nViews+1 WHERE nIdCode IN (".$blogids.")"; } $result = mysql_query($sql,$con); if ($result==false){ print "<li>Problem with SQL<br>[".$sql."]</li>\n"; } } } Last edited by sbarros (2011-01-08 18:21:52) How can I get rid of "Notice:Array to string conversion on line 78" error from this code? can i get a little help please? This is line 78 : $table .= $columnValue; Basically this code's supposed to do is to group the values from grpa, grpb of datatb to 4 different categories according to their value. and as end result, category index number of each category is put into the html table. Thanks.
<?php include ("configd.php"); $sql = "SELECT grpa, grpb From datatb"; $result = $conn->query($sql); //categories $cat = [ 4 => [1, 2, 3, 4], 3 => [5, 6], 2 => [7, 8], 1 => [9, 10] ]; while ($row = $result->fetch_assoc()) { foreach ($cat as $catKey => $catValue) { $columns[$catKey] = array_filter($row, function ($col) use ($cat, $catKey) { if (in_array($col, $cat[$catKey])) { return true; } }); } $output[] = $columns; } // the output $table = <<<EOT <table class='maintable'> <tr><th>9:10</th></tr> <tr><th>7:8</th></tr> <tr><th>5:6</th></tr> <tr><th>1:4</th></tr> </table> EOT; foreach ($output as $row) { $table .= "<table class='maintable'>"; foreach ($row as $columnKey => $columnValue) { $table .= "<tr>"; $table .= "<td>"; $table .= $columnValue; $table .= "</td>"; } $table .= "</tr>"; $table .= "</table>"; } echo $table; ?> Edited June 30, 2020 by mattix small additions. If I wanted to print a string that contains a variable that also contains an array, how would I do so? I want to put the resulting echo into a log file. Example: “These are the books: $userArray and these are the pages: $pagesArray”; With just an array, I can use print_r($array, true) to get an array formatted for use in a string (which works well for my purposes) but this doesn’t work with two arrays unless I do this manually. (Such as setting the $user_array = print_r($userArray). But I want to write a function that will take a string, potentially containing arrays (as variables), and interpolate/make them legible for humans. (Some of the arrays are also multidimensional.) But it looks like I can't even concatenate a string and an array. $string = $string . $array. gives an error, array to string conversion. I don’t understand PHP very well so please explain what is going on here. and the best way to record something like the Example above. Hi everybody, I need some help about how to convert string to array name. I have the following function which pass $_REQUEST type as parameter. It is not working because I don't know how to convert $method to $_GET or $_POST in a proper way. Do anybody know how? Code: [Select] function validateIfFilled($method, $fields) { $exploded=explode(",",$fields); foreach($exploded as $field){ if(empty($method[trim($field)])){ return false; } } return true; }; if(!validateIfFilled('$_GET', "email, password, address")) ... Thank you! I have in ONE MySQL database row a string of ID's like this: Name of Row: Values: Post IDs 10 14 52 37 And now I want to fetch those ID's explode them (by the space) and then use them as an array, like this: $array[] = explode(" ", $query); echo $array[0]; // 10 echo $array[1]; // 14 echo $array[2]; // 52 Is this possible, if yes how can I do this? Hello I am facing a problem which i can not handle. I appreciate for any help. My Database is: Code: [Select] CREATE TABLE IF NOT EXISTS `shops` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `options` text, `user_name` varchar(250) NOT NULL , PRIMARY KEY (`id`), UNIQUE KEY `user_name` (`user_name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='user data stored' AUTO_INCREMENT=1 ; And some sample data as below: Code: [Select] INSERT INTO `users` (`id`, `options`, `user_name`) VALUES (1, 'apple-orange-grape-bmw-toyota-fig-', 'user1'), (4, 'apple-tomato-pc-notebook-yellow-', 'user2'), (5, 'blue-green-orange-cdrom-', 'user3'), (6, 'orange-yellow-blue-pink-bread-', 'user4'); How can i display how many apples or green or any item selected by user? So far i tried in_array, array_count_values but seems no one is working. Regards |