I have one object array data coming below way.
$rooms= Single room,Single room,Single room ;
Here i want to display data below format
3 X Single room
For example rooms coming below format
Single room, Double room , Single room
then i need to out put is
2x single room
1x Double room
How to get like this ,Please tell me, i tried array_count_values and array_unique but not get result. Please any one know tell me
$str = rtrim(implode(",",explode("#", Single Room#DOuble Room#Single Room)));
$ss= str_replace(' ','',$str);
$ss1= str_replace(',',' ',$ss);
$rooms = explode(' ', $ss1);
//Count each occurence of values
$countedValues = array_count_values($rooms);
//Build strings from value and display them.
foreach( $countedValues as $roomType=>$count ){
echo $count . 'x ' . $roomType . '<br />';
}
I don't know how you're using array_count_values because you haven't posted your code, please post your code in future. Below is a working example that gives your desired output.
<?php
$rooms = "Single room,Single room,Single room,Double room";
$rooms = explode(',', $rooms); // array of rooms
//Count each occurence of values
$countedValues = array_count_values($rooms);
//Build strings from value and display them.
foreach( $countedValues as $roomType=>$count ){
echo $count . 'x ' . $roomType . '<br />';
}
?>
This gave me the output:
3x Single room
1x Double room
Please note that your question includes this:
$rooms= Single room,Single room,Single room ;
this is not a valid array format. You should use this instead:
$rooms = array("Single room","Single room","Single room");
Related
So i have an array full of random things (lets say fruits)
$fruit = array ("Banana", "Strawberry", "Apple",);
which is followed by a
echo implode (glue ' and ', $fruit);
which is supposed to list every single fruit that appears in the array
Now, how do I count the amount of items that appear wihtin in the list? As in how do i make the code show that it's 3 items
You can use the count() method of php.
Reference
For showing the amount you can use it like that:
echo "Amount: " . count($fruit);
You can use Count().
$fruit = array ("Banana", "Strawberry", "Apple",);
echo implode(' and ', $fruit) . " is " . count($fruit) . " fruits";
// Banana and Strawberry and Apple is 3 fruits
https://3v4l.org/19LqD
I have a sting that looks like this
$storelist = "‘F Mart (6)’, ‘ACME (5)’, 'J/M Store (17)'";
I want to break out selected companies and the number of locations by comparing the first string to a second string like
$selectedstores = "‘F Mart’, 'J/M Store";
And output a sting like
$selectedwithnumber = "‘F Mart (6)’, 'J/M Store (17)'"
There could be 1 to 15 companies in a string and the location number varies but the apostrophes and parenthesis are standard. I hope there an easy way to do this as I have no idea where to start. Thanks in advance.
You can use explode function to split arrays to parts, and use preg_replace function to remove number of companies (with brackets) from first string. below you can find working example:
$storelist = "‘F Mart (6)’, ‘ACME (5)’, 'J/M Store (17)'";
$selectedstores = "‘F Mart’, 'J/M Store'";
//split second array
$selectedArray = explode(', ', $selectedstores);
$resultArray = array();
//split first array
foreach(explode(', ', $storelist) as $storeWithNumber) {
//remove " (number)" from each part
$store = preg_replace('/\s+\(\d+\)/', '', $storeWithNumber);
//check if current part is on selected list
if (in_array($store, $selectedArray)) {
$resultArray[] = $storeWithNumber;
}
}
$selectedwithnumber = implode(', ', $resultArray);
echo $selectedwithnumber.PHP_EOL;
result is:
‘F Mart (6)’, 'J/M Store (17)'
This will get what you need based on your description. It breaks up your strings into arrays and then uses a nested foreach loop to do the comparisons. I used string functions over regular expression functions in case speed becomes an issue. It does however require that your main string of stores follows the conventions you described.
<?php
$storelist = "'F Mart (6)', 'ACME (5)', 'J/M Store (17)'";
$selectedstores = "'F Mart', 'J/M Store'";
$stores = explode(",", $storelist);
$selected = explode(",", $selectedstores);
$newStoreList = array();
foreach($selected as $selectedStore) {
foreach($stores as $store) {
$s = trim( $selectedStore, "' ");
if(strstr($store, $s)) {
$newStoreList[] = $store;
}
}
}
$newStoreList = implode(",", $newStoreList);
echo $newStoreList;
?>
This will output: 'F Mart (6)', 'J/M Store (17)'
Hope that helps!
Sorry for a slight duplication of Q but I think the previous answers are now depreciated (I've seen that in PHP 5.3 you need you use MySQLi_fetch_array())
I'm using jpgraph and trying to pull my data from a MySQL database. I have the following code which pulls the figures I need and when I echo the result it spits out the answers one by one no problem but it won't then put it into an array.
I'm trying to replace a line which is
$ydata = array(1,2,3,4,5,6,7);
//query
$sql = "SELECT CONCAT( 'Week ', WEEK( TimeofCompletion ) , ' ', YEAR( TimeofCompletion ) ) AS Week, Count( * ) AS VolumeOfAnswers
FROM table01
GROUP BY WEEK( TimeofCompletion ) , YEAR( TimeofCompletion )
ORDER BY TimeofCompletion";
$ydata = array();
while($row = mysql_fetch_array($sql)){
// Create a temporary array
$temp = array();
$temp[] = "".$row['VolumeOfAnswers']."";
$ydata = '['. implode(', ', $temp) . ']';
}
Any suggestions how I would get the output by row into an array?
Regards
Maudise
$temp[] = "".$row['VolumeOfAnswers'].""; //what this suppose to do?
i assume you want quotes around i would add single quote inside
$temp[] = "'".$row['VolumeOfAnswers']."'";
otherwise you dont need double quotes at all so i would remove them. After that your array will hold the values from the database.
according to documentation mysql_fetch_array is deprecated and you should be using PDO or MySQLi. But if you still want to use it, i would suggest using mysql_fetch_assoc instead.
Now about the question:
while($row = mysql_fetch_array($sql)){
// Create a temporary array
$temp = array();
$temp[] = "".$row['VolumeOfAnswers']."";
//why is this here? should be outside of while loop shouldnt it?
$ydata = '['. implode(', ', $temp) . ']';
}
your $ydata always gets overwritten and holds only the last element of $temp array. Either move $ydata outside of while loop or use array_merge($ydata, $temp);
I'm trying to turn MySQL data into an array and then calculate the sum of that array.
$weight = ($product['av_id_1'])*$val; // get attribute values
$weightsub = explode(" ", $weight); // convert string to array
echo array_sum($weightsub);
I'm getting an output but its not what I expected, instead of a single integer its spaced integers like "30 40 50".
Where am I going wrong?
Thanks
$weightsub = explode(" ", $product['av_id_1']); // convert string to array
echo array_sum($weightsub)*$val;
First you need to extract all numbers using explode. Then apply array_sum to sum all numbers in the array, and multiply the sum by $val.
If this doesn't work as intended, you can easily do some basic debugging by using echo and print_r on each variable or result:
echo '$product[av_id_1] = <br>';
print_r($product['av_id_1']);
$weightsub = explode(" ", $product['av_id_1']); // convert string to array
echo '$weightsub = <br>';
print_r($weightsub);
echo "<br>\$val = $val<br>";
echo 'Sum = ' . array_sum($weightsub) . '<br>';
echo array_sum($weightsub)*$val;
im creating a search feature that will allow a user to type in a question, my code will then match as many words as possible with the questions already in my MySQL database and display the top 5 results depending on the amount of words that are matched in the question.
I use a count() function which counts the number of matching words, however at the moment the results shown are displayed as the first 5 results in the database that have a 50% word match or more. I want the results to be shown as the highest match first and work its way down for every result in the database but only show the top 5.
Here is the code I have
<?php
include("config.php");
$search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING); //User enetered data
$search_term = str_replace ("?", "", $search_term); //remove any question marks from string
$search_count = str_word_count($search_term); //count words of string entered by user
$array = explode(" ", $search_term); //Seperate user enterd data
foreach ($array as $key=>$word) {
$array[$key] = " title LIKE '%".$word."%' "; //creates condition for MySQL query
}
$q = "SELECT * FROM posts WHERE " . implode(' OR ', $array); //Query to select data with word matches
$r = mysql_query($q);
$count = 0; //counter to limit results shown
while($row = mysql_fetch_assoc($r)){
$thetitle = $row['title']; //result from query
$thetitle = str_replace ("?", "", $thetitle); //remove any question marks from string
$title_array[] = $thetitle; //creating array for query results
$newarray = explode(" ", $search_term); //Seperate user enterd data again
foreach($title_array as $key => $value) {
$thenewarray = explode(" ", $value); //Seperate each result from query
$wordmatch = array_diff_key($thenewarray, array_flip($newarray));
$result = array_intersect($newarray, $wordmatch);
$matchingwords = count($result); //Count the number of matching words from
//user entered data and the database query
}
if(mysql_num_rows($r)==0)//no result found
{
echo "<div id='search-status'>No result found!</div>";
}
else //result found
{
echo "<ul>";
$title = $row['title'];
$percentage = '.5'; //percentage to take of search word count
$percent = $search_count - ($search_count * $percentage); //take percentage off word count
if ($matchingwords >= $percent){
?>
<li><a href='<?php echo $row['url']; ?>'><?php echo $title ?><i> No. matching words: <?php echo $matchingwords; ?></i></a></li>
<?php
$count++;
if ($count == 5) {break;
}
}else{
}
}
echo "</ul>";
}
?>
The image below shows the what happens when I search "How to make my own website" in the search bar. I already have several questions in the database for testing which are all similar questions and one the last entry is an exact match to the question I asked, but as its currently showing them as the first 5 mathing results, it ignores the full match.
Here is the results from that search.
I have added a bit of code which shows how many word matches there are in each question just so you can see it working a bit better. Also its a coincidence that its in ascending order, it is showing the first 5 matching results in the database.
What code do I need to add to this to arrange it so that it shows the closest match from the entire database first then the second best match, third etc...?
Either you use a nested SQL query where you can order by count or load the values to array php array first and then sort the array. Using SQL is very efficient && faster.
Multi Dimension Array Sorting
select column1, column2,..., LENGTH(titlecolumn) - LENGTH(REPLACE(titlecolumn, '$search term', '')) AS nummatchwords from posts where " . implode(' OR ', $array) order by nummatchwords;