Combine data from array into one variable - php

I'm trying to combine several results from an array into one variable.
$sqlNameForCode = "Select dim_InvoiceRef from dimensions"." Where dim_FileRef = '".$addRow[$FieldName]."'";
$qryNameForCode = mysql_Query($sqlNameForCode);
While($arrNameForCode = mysql_fetch_array($qryNameForCode)) {
$addRow[$FieldName] = $arrNameForCode['dim_InvoiceRef'];
}
I need the variable $addRow[$FieldName] to contain all the fields taken from the array. However because it's within the While loop only the last field is ever left in the variable.
Example, the query pulls the following results
Apple
Banana
Orange
I need echo $addRow[$FieldName] to show Apple Banana Orange, at the moment it just equals Orange.
Any help would be great thanks!

You need to make it into an array
While($arrNameForCode = mysql_fetch_array($qryNameForCode)) {
$addRow[$FieldName][] = $arrNameForCode['dim_InvoiceRef']; //notice the extra braces
}
echo implode(' ', $addRow[$FieldName]); //prints the values in the array separated by a space
Or directly assign it to a string
$addRow[$FieldName] = "";//defaults
While($arrNameForCode = mysql_fetch_array($qryNameForCode)) {
$addRow[$FieldName] .= $arrNameForCode['dim_InvoiceRef']; //string concatenation
}
echo $addRow[$FieldName];

Here's a MySQL-based solution that you might find easier:
$sql = "SELECT GROUP_CONCAT(dim_InvoiceRef SEPARATOR ' ') FROM dimensions WHERE dim_FileRef = '".$field."'";
$query = mysql_query($sql);
$result = mysql_fetch_row($query);
echo $result[0]; // Should show 'Apple Orange Banana' etc.
I took the liberty of renaming some variables in your example to make it easier to understand. Unless you need to do different things with the same data later on in the program, this should work.

Related

How to break zero index comma separated value into individual string in php

I want to break comma seperated values which are retrieved from database and then put each individual in a string and print it in a for loop only. I am getting the values from database but i am not be able to break values. Below is the code what i have done right till now.Please help to solve my issue. Thanks in advance.
$query="select * from create_segment";
$result = mysql_query($query,$link) or die(mysql_error());
$number_of_segment=mysql_num_rows($result);
while($row=mysql_fetch_assoc($result))
{
$segments[]=$row;
}
foreach($segments as $success) {
$thePostIdArray = explode(', ', $success['subjects']);
for($i=0; $i < count($thePostIdArray); $i++)
{
echo "string...".$strings=$thePostIdArray[$i];
}
}
It output:
string...1,2,3,4,5,6,7,8,9,10
string...1,2,3,4,5,6,7,8
but i want something like this:
for(......)
{
echo "values...".$i;
}
which should output
values...1
values...2
values...3 and so on.
my database structure is like:
id subjects
1 1,2,3,4,5
2 1,2,7
Please try to use ',' instead of ', ' in your
explode(', ', $success['subjects']);
statement so it would look like:
explode(',', $success['subjects']);
Use:
explode(',', $success['subjects'])
You had a space after the comma, but there are no spaces in the database values.
If you have the opportunity to change the database structure you should convert that table into something like this:
Id Subject
1 1
1 2
1 3
2 1
etc.
It will make your queries much easier, and it the right way to go. It will also make it easier for you in the future do join this table with other tables to get the desired results. I know this doesn't answer your questions, but some good advice will never hurt. One of the other answers will answer your question directly.
$query="select * from create_segment";
$result = mysql_query($query,$link) or die(mysql_error());
$number_of_segment=mysql_num_rows($result);
while($row = mysql_fetch_assoc($result))
{
foreach (explode(',',$row['subjects']) as $value){
echo echo "string... {$row['id']} " . $value . '<br />';
}
}

Fetch result from database to multiple variables

I have a site were the user fills a form and all data is stored in a database, when the user enter his/hers page all the added data is visible. Today I´m doing this but in a lot of code rows and there is for sure a much smoother way to do this.
Here´s a look of how I have done it today:
$query = mysqli_query($dbhandle, "SELECT * FROM ..."); // ... added now
$row = mysqli_fetch_assoc($query);
$m0 = $row['m1'];
$m1 = $row['m2'];
$m2 = $row['m3'];
$m3 = $row['m4'];
...
$m47 = $row['m48'];
$firstPlace = $row['firstPlace '];
$secondPlace = $row['secondPlace '];
$thirdPlace = $row['thirdPlace '];
$fourthPlace= $row['fourthPlace'];
As you can see there are a lot of rows of code. What I would like to do is to loop through my query and then add the right value in the database to the right value in the form.
Appreciate help.
There definitely are many alternative (and in every possible sense of the word) better ways to go about your business.
For a kickoff: ask yourself what an array actually is. An array is a collection of data. You store them together because one value of that array in itself doesn't mean much. The data in an array belongs together. Why then, assign it to individual variables in the first place?
Of course, your $row array has keys like $row['m1'], which you assign to a variable called $m0. so the names of the fields in the database don't quite match the names your code uses. That's something that you can, quite easily, fix by changing your query: use aliasses for those fields:
SELECT m1 as m0, ... FROM
Now your array will have a key called m0, instead of m1. This reduces the rest of your code down to:
$row = mysqli_fetch_assoc($query);
echo 'M0: ', $row['m0'];//<-- use m0 value here.
Alternatively, you could use a second array that maps these field-names to the name you want to use in your code:
$map = array(
'm0' => 'm1'
);
echo 'M0: ', $row[$map['m0']];//use value of m0, which is the actual key if the $row array
Still, if you are hell-bound on unmaintainable, messy, error-prone and just awful code, you could use variable variables:
foreach ($row as $key => $value)
{
$$key = $val;
}
Note the double $ in $$key. This is like saying "the variable that is called whatever the value of $key is". If $key is firstname, the code above evaluates to $firstname = $value. But whatever you do: forget this is possible. It's like an enema: yes, it's possible, but you don't want one if you can avoid it. And in this case, you clearly can avoid it.
Loop through the $row var grabbing the key and value. If key starts with "m" followed by a 1 or 2 digit number, get the number, subtract one, concatenate it with "m", and assign the value. Otherwise just interpolate key into variable name and assign value.
foreach ( $row as $key => $value ) {
if ( preg_match('/^m(\d{1,2})/', $key, $matches) ) {
${'m' . ($matches[1] - 1)} = $value;
}
else { $$key = $value; }
}
In the above example, $row['m1'] value gets assigned to var $m0, and $row['firstPlace'] to var $firstPlace, etc.

Multidimensional array: implode both outer and inner arrays‏

Using this sample multidimensional array (of a palette which contains colours, which in turn contains their respective shades), let’s say I would like to display the colours in an imploded list (comma-separated) and, if applicable, its respective shades in brackets, also in an imploded (comma-separated) list.
I can easily implode the inner array (shades), but cannot figure out how to do that with the outer array (colours) given it contains the array of shades which must be run through for each colour.
I’ve seen there are several solutions for imploding a multidimensional array, but these seem to be without requiring running through a possible inner array for each. Perhaps there is another method by which to separate the entries with a comma?
And while I’m on the subject, is there a way of replacing the last comma of an imploded string with ‘and’?
Thanks in advance.
$sql = "SELECT DISTINCT colour_id, colour_nm, colour_url
FROM palettecolours
INNER JOIN colour ON colourid = colour_id
WHERE paletteid = '$palette_id'";
while ($row = mysqli_fetch_array($result))
{
$colour = '' . $row['colour_url'] . '';
$colours[$row['colour_id']] = array('colour' => $colour, 'shades' => array());
}
$sql = "SELECT colourid, shade_name, shade_url
FROM palettecolours
INNER JOIN shade ON shadeid = shade_id
WHERE paletteid = '$palette_id'";
while ($row = mysqli_fetch_array($result))
{
$shade = '' . $row['shade_url'] . '';
$colours[$row['colourid']]['shades'][] = array('shade' => $shade);
}
<?php foreach ($colours as $colour): ?>
<?php echo $colour['colour']; ?>
<?php if(!empty($colour['shades'])) { ?>(<?php echo implode(", ", $colour['shades']); ?>)<?php } ?>
<?php endforeach; ?>
CURRENT DISPLAY:-
Red (Magenta, Burgundy, Crimson) Blue Green Yellow (Egyptian Cotton, Magnolia) White (Soft Moon)
DESIRED OUTCOME:-
Red (Magenta, Burgundy, Crimson), Blue, Green, Yellow (Egyptian Cotton, Magnolia), White (Soft Moon)
How about recursive functions? Something like
function array_implode_recursive($glue, $data, $before = '(', $after = ')') {
//Loop through every child and check whether it is an array or not and implode it if so
foreach($data as &$element) {
if (is_array($element)) {
$element = $before . array_implode_recursive($glue, $element) . $after;
}
}
//It's really safe to erase this variable as sometimes PHP has fun with them
unset($element);
return implode($glue, $data);
}
Use it like this
$mydata = implode_recursive(', ', $data);
$mydata = implode_recursive(', ', $data, '[', ']');
Hope it helped
Since you know what your array looks like and it appears to have keys you could try something similar to what I've done here.

Get Popular words in PHP+MySQL

How do I go about getting the most popular words from multiple content tables in PHP/MySQL.
For example, I have a table forum_post with forum post; this contains a subject and content.
Besides these I have multiple other tables with different fields which could also contain content to be analysed.
I would probably myself go fetch all the content, strip (possible) html explode the string on spaces. remove quotes and comma's etc. and just count the words which are not common by saving an array whilst running through all the words.
My main question is if someone knows of a method which might be easier or faster.
I couldn't seem to find any helpful answers about this it might be the wrong search patterns.
Somebody's already done it.
The magic you're looking for is a php function called str_word_count().
In my example code below, if you get a lot of extraneous words from this you'll need to write custom stripping to remove them. Additionally you'll want to strip all of the html tags from the words and other characters as well.
I use something similar to this for keyword generation (obviously that code is proprietary). In short we're taking provided text, we're checking the word frequency and if the words come up in order we're sorting them in an array based on priority. So the most frequent words will be first in the output. We're not counting words that only occur once.
<?php
$text = "your text.";
//Setup the array for storing word counts
$freqData = array();
foreach( str_word_count( $text, 1 ) as $words ){
// For each word found in the frequency table, increment its value by one
array_key_exists( $words, $freqData ) ? $freqData[ $words ]++ : $freqData[ $words ] = 1;
}
$list = '';
arsort($freqData);
foreach ($freqData as $word=>$count){
if ($count > 2){
$list .= "$word ";
}
}
if (empty($list)){
$list = "Not enough duplicate words for popularity contest.";
}
echo $list;
?>
I see you've accepted an answer, but I want to give you an alternative that might be more flexible in a sense: (Decide for yourself :-)) I've not tested the code, but I think you get the picture. $dbh is a PDO connection object. It's then up to you what you want to do with the resulting $words array.
<?php
$words = array();
$tableName = 'party'; //The name of the table
countWordsFromTable($words, $tableName)
$tableName = 'party2'; //The name of the table
countWordsFromTable($words, $tableName)
//Example output array:
/*
$words['word'][0] = 'happy'; //Happy from table party
$words['wordcount'][0] = 5;
$words['word'][1] = 'bulldog'; //Bulldog from table party2
$words['wordcount'][1] = 15;
$words['word'][2] = 'pokerface'; //Pokerface from table party2
$words['wordcount'][2] = 2;
*/
$maxValues = array_keys($words, max($words)); //Get all keys with indexes of max values of $words-array
$popularIndex = $maxValues[0]; //Get only one value...
$mostPopularWord = $words[$popularIndex];
function countWordsFromTable(&$words, $tableName) {
//Get all fields from specific table
$q = $dbh->prepare("DESCRIBE :tableName");
$q->execute(array(':tableName' = > $tableName));
$tableFields = $q->fetchAll(PDO::FETCH_COLUMN);
//Go through all fields and store count of words and their content in array $words
foreach($tableFields as $dbCol) {
$wordCountQuery = "SELECT :dbCol as word, LENGTH(:dbCol) - LENGTH(REPLACE(:dbCol, ' ', ''))+1 AS wordcount FROM :tableName"; //Get count and the content of words from every column in db
$q = $dbh->prepare($wordCountQuery);
$q->execute(array(':dbCol' = > $dbCol));
$wrds = $q->fetchAll(PDO::FETCH_ASSOC);
//Add result to array $words
foreach($wrds as $w) {
$words['word'][] = $w['word'];
$words['wordcount'][] = $w['wordcount'];
}
}
}
?>

Append string to itself, 'X' number of times (Where 'x' is a variable)

I have a HTML page where a user can select multiple values in a checklist. Depending on the number of items selected, that's how many times I would like to append a variable to itself, separated by commas (if that makes sense)
For example, if my string was $string = "'$apple'" (yes, my string is meant to be formatted this way, you'll see why) and the user selected 3 items from the checklist, my string would end up being:
"'$apple', '$apple', '$apple'"
When the user submits the page, here's the PHP:
$category = mysql_real_escape_string($_POST['category']);
$string = 'test';
if (count($category) === 1) {
//donothing
}
else{
$category = implode(",",$category);
}
$numcat = count($category); //count number of items in $category, save value to $numcat
$query = mysql_query("INSERT INTO table (". $category .") VALUES ('$string')");
For reference, if the user has selected "apple, banana, grape" from the HTML form, I want the query to essentially look like this:
$query = mysql_query("INSERT INTO table (apple, banana, grape) VALUES ('$string', '$string', '$string')");
Another example, if the user has selected just "apple, grape" from the HTML form, I want it to end up looking like this:
$query = mysql_query("INSERT INTO table (apple, grape) VALUES ('$string', '$string')");
The INSERT INTO table (apple, grape) is already solved by just doing INSERT INTO table (". $category .") since I have imploded it and seperated by commas, but then I also need the string to display 'X' amount of times in VALUES, depending on the result from count($category)?
How can I do this?
It looks to me that you want to take a variable and a count and make a string from it. If that is the case, will this work:
$value = "'x'";
$count = 3;
$a = array_fill(0, $count, $value);
$str = implode(',', $a);
Then, $str will contain "'x','x','x'".
You can ask why I didn't use str_repeat. I haven't seen a way to use a glue with that. The implode function lets me use , as the glue. I just needed to make it an array first.

Categories