I fetched record from mysql and resultent is in array:
Array ( [Logodesign] => 130 [Webdesign] => 80 [Printdesign] => 72 [Illustrationdesign] => 49 [iPhoneportfolio] => 23 )
and I want to show all categories with their total rows in tag like
to do so i coded:
$q = mysql_query("SELECT
SUM(IF(cat = 'logodesignportfolio',1,0)) AS Logodesign,
SUM(IF(cat = 'websitedesignportfolio',1,0)) AS Webdesign,
SUM(IF(cat = 'printdesignportfolio',1,0)) AS Printdesign,
SUM(IF(cat = 'illustrationdesignportfolio',1,0)) AS Illustrationdesign,
SUM(IF(cat = 'iphoneportfolio',1,0)) AS iPhoneportfolio
FROM portfolio");
$f = mysql_fetch_assoc($q);
print_r($f);
echo "<br />";
echo "<select>";
foreach($f as $k){
echo "<option>".$f.' - '.$k."</option>";
}
echo "</select>";
but it shows:
Use this:
foreach($f as $k => $a){
echo "<option>".$k.' - '.$a."</option>";
}
Related
I have list with categories that sometimes appear duplicate. I want to them belonging to the same category as in groups. Current output is as follows:
Mercedes
Vito
Mercedes
A Klasse
Opel
Corsa
Mercedes
CLA
I want them to print like:
Mercedes
Vito
A Klasse
CLA
Opel
Corsa
my code:
$string = json_decode('{"cars_array":[{"brand":"Mercedes","model":"Vito"},{"brand":"Mercedes","model":"A Klasse"},{"brand":"Opel","model":"Corsa"},{"brand":"Mercedes","model":"CLA"}]}',true);
$catArray = array();
foreach ($string['cars_array'] as $k => $product) {
echo $product['brand']."\n";
echo $product['model']."\n\n";
}
What I have tried so far:
$string = json_decode('{"cars_array":[{"brand":"Mercedes","model":"Vito"},{"brand":"Mercedes","model":"A Klasse"},{"brand":"Opel","model":"Corsa"},{"brand":"Mercedes","model":"CLA"}]}',true);
$catArray = array();
foreach ($string['cars_array'] as $k => $product) {
if (array_key_exists($product['brand'], $catArray)) {
$catArray[$product['brand']] = array('model' => $product['model'] );
}else{
$catArray[$product['brand']] = $product['brand'];
$catArray[$product['brand']] = array('model' => $product['model'] );
}
}
var_dump($catArray);
You can group items by using a named array, then assign values by pushing them with [] syntax
$string = json_decode('{"cars_array":[{"brand":"Mercedes","model":"Vito"},{"brand":"Mercedes","model":"A Klasse"},{"brand":"Opel","model":"Corsa"},{"brand":"Mercedes","model":"CLA"}]}',true);
$catArray = array();
foreach ($string['cars_array'] as $k => $product) {
// create an array grouped on brand’s value
$catArray[$product['brand']][] = $product['model'];
echo $product['brand']."\n";
echo $product['model']."\n\n";
}
foreach($catArray as $brand => $modelList) {
print "$brand\n";
foreach($modelList as $model) {
print "$model\n";
}
print "\n";
}
try to use array unique in $string
$string_arr = array_unique($string);
then Implode it
$echo_arr = implode($string_arr)
echo $echo_arr;
After 1st answer my output is one value missing my ratting lenght is According to Array2 not Array !,,,,,Input:
I want this output:
My output is getting 0,0,0,0
I want to compare two arrays with different length, if matches the add the value, if not then add "0" and skip after assign and go to first loop
My code:
for($i=0;$i<count($custt1);$i++){
for($j=0;$j<count($items);$j++){
if($items[$j]==$custt1[$i]){
$x[$j]=$rating[$j];
}
else{
$x[$j]=0;
}
}
for($j=0;$j<count($items1);$j++){
if($items1[$j]==$custt1[$i]){
$y[$j]=$rating1[$j];
}
else{
$y[$j]=0;
}
}
}
I want to save in x and y array if value present then add rating otherwise "0" and go to first loop but I am facing in index 0 if value not present add 0 and on 8 indexes. Hope you understand my explanation and please help me to solve this.
now my output is by applying 1st answer
<br />
<b>Notice</b>: Undefined offset: 5 in
<b>C:\xampp\htdocs\Rest\new2.php</b> on line
<b>79</b>
<br />
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 0
[4] => 5
[5] =>
[6] => 0
[7] => 0
[8] => 0
)
Because i am implementing recommendation system
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "hfc";
$array;
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($connection) {
$sql1="SELECT item_name
from feedback
GROUP BY item_name";
$sql="SELECT customer_email_address AS customeremail,
GROUP_CONCAT(
DISTINCT CONCAT(cook_email_address,'-',item_name,'-',rating)
) AS uniqueItem
FROM feedback
GROUP BY customer_email_address";
$result = mysqli_query($connection, $sql);
while ($row = mysqli_fetch_array($result))
{
$customer_email[] = $row['customeremail'];
$cust1[]= $row['uniqueItem'].",";
}
$item[] = explode(",",$cust1[0]);
for($i=0;$i<count($item[0])-1;$i++){
$item_rating[] = explode("-",$item[0][$i]);
}
print_r ($item_rating);
for($i=0;$i<count($item_rating);$i++){
$items[]=$item_rating[$i][1];
$rating[]=$item_rating[$i][2];
}
$item1[] = explode(",",$cust1[1]);
for($i=0;$i<count($item1[0])-1;$i++){
$item_rating1[] = explode("-",$item1[0][$i]);
}
print_r ($item_rating1);
for($i=0;$i<count($item_rating1);$i++){
$items1[]=$item_rating1[$i][1];
$rating1[]=$item_rating1[$i][2];
}
$result1 = mysqli_query($connection, $sql1);
while ($row = mysqli_fetch_array($result1))
{
$custt1[]= $row['item_name'];
}
print_r ($custt1);
print_r ($items);
$output = array();
foreach ($custt1 as $i =>$item) {
if (in_array($item, $items)) {
$output[] = $rating[$i];
} else {
$output[] = 0;
}
}
print_r ($output);
for($i=0;$i<count($custt1);$i++){
for($j=0;$j<count($items);$j++){
if($items[$j]==$custt1[$i]){
$x[$i]=$rating[$j];
}
else{
$x[$i]=0;
}
}
for($j=0;$j<count($items1);$j++){
if($items1[$j]==$custt1[$i]){
$y[$j]=$rating1[$j];
}
else{
$y[$j]=0;
}
}
}
print_r ($x);
print_r ($y);
for($i1=0;$i1<count($custt1);$i1++)
{
$array[]=explode(",",$custt1[$i1]);
}
// echo count($array);
// print_r($custt1)."<br>";
/*for($i=0;$i<count($array);$i++)
{
for($y=1;$y<count($array);$y++)
{
$pearson=Corr($array[$i],$array[$y],$c=count($array));
}
}*/
$pearson=Corr($array);
echo $pearson;
}
function Corr(&$arr){
$x=$arr[0];
$y=$arr[1];
$length=count($x)-1;
$mean1=array_sum($x)/ $length;
$mean2=array_sum($y)/ $length;
echo $mean1."mean of x";
echo $mean2."mean of y";
echo "\n";
//echo $mean2;
$a=0;
$b=0;
$axb=0;
$a2=0;
$b2=0;
for($i=0;$i<$length;$i++)
{
$a=$x[$i]-$mean1;
$b=$y[$i]-$mean2;
$axb=$axb+($a*$b);
$a2=$a2+ pow($a,2);
$b2=$b2+ pow($b,2);
$corr= $axb / sqrt($a2*$b2);
}
return $corr;
}
?>
Use in_array() to tell if the element of array 1 is in array 2.
$output = array();
foreach ($array1 as $i => $item) {
if (in_array($item, $array2)) {
$output[] = $rating[$i];
} else {
$output[] = 0;
}
}
This is my function
$dataArray = array();
$results = mysqli_query($mysqli, ("SELECT CONCAT ('US-', medicare_provider_charge_inpatient_drg100_fy2011.`Provider State`) AS `Provider State`,
sum(ROUND(medicare_provider_charge_inpatient_drg100_fy2011.`Total Discharges`, 2)) AS `Total Discharges`
FROM medicare_provider_charge_inpatient_drg100_fy2011
WHERE medicare_provider_charge_inpatient_drg100_fy2011.`Provider Name` LIKE '%" . $hospital_name . "'
GROUP BY CONCAT ('US-', medicare_provider_charge_inpatient_drg100_fy2011.`Provider State`)"));
while ($row = mysqli_fetch_assoc($results)) {
$dataArray[] = $row;
}
I want to display data in following format
[Provider State, Total Discharges],
[US-AL,2051],
[US-TN,6982]
the dump of $dataArray gives me
Array
(
[0] => Array
(
[Provider State] => US-AL
[Total Discharges] => 2051.00
)
[1] => Array
(
[Provider State] => US-TN
[Total Discharges] => 6982.00
)
)
while ($row = mysqli_fetch_assoc($results)) {
$dataArray[] = $row["Provider State"]. "," .$row["Total Discharges"];
}
That should make your data into a single-dimensional-array.
You just need to work with the data to display the way you want. Print first the column names and then the data. I made this example to work for any number of fields:
// Print the first row with column names
$firstRow = array_keys(reset($dataArray));
$output = array();
foreach($firstRow as $val) {
$output[] = $val;
}
echo '['.implode(',',$output).']'."\n";
// Print all the data
foreach($dataArray as $row) {
$output = array();
foreach($row as $col) {
$output[] = $col;
}
echo '['.implode(',',$output).']'."\n";
}
If you need such structure of array, use this (but it is strange):
$newStructure = array();
$newStructure[] = "Provider State, Total Discharges";
while ($row = mysqli_fetch_assoc($results)) {
$newStructure[] = $row['Provider State'] . ',' . $row['Total Discharges'];
}
If you want to just display data, use this:
echo "Provider State, Total Discharges";
while ($row = mysqli_fetch_assoc($results)) {
echo = $row['Provider State'] . ',' . $row['Total Discharges'];
}
I am trying to display the array data in a specific way in a table, so I am needing to format my array like this:
Leafy Life - Aspley - All Green
Callistemon1 - 33 - -
Callistemon2 - - - 3.59
Acronychia - - 22.5 -
I have tried many times, but my knowledge is limited and would really appreciate it if anyone can point me in the right direction, or even if you have time to adjust my code that would be very much appreciated.
<?php
$options = array(
array("plant" => "Callistemon Kings Park Special 300 mm","nursery" => "A Leafy Life","price" => "33"),
array("plant" => "Callistemon Kings Park Special 300 mm","nursery" => "Alpine Nurseries Alstonville","price" => "23"),
array("plant" => "Callistemon Kings Park Special 140 mm","nursery" => "All Green Nursery","price" => "3.59"),
array("plant" => "Acronychia imperforata 300 mm","nursery" => "Aspley Nursery","price" => "22.5"),
array("plant" => "Acronychia imperforata 300 mm","nursery" => "All Green Nursery","price" => "23"),
array("plant" => "Metrosideros collina Little Dugald 140 mm","nursery" => "Accent Plants","price" => "5.25"),
);
$newOptions = array();
foreach ($options as $option) {
$plant = $option['plant'];
$nursery = $option['nursery'];
$price = $option['price'];
$newOptions[$plant][$nursery] = $price;
}
print_r($newOptions);
echo "<table cellpadding='0' cellspacing='0' border='2'>";
echo "<thead>";
echo "<th></th>";
foreach($newOptions as $key => $row)
{
foreach($row as $k => $v)
{
print_r($k);
echo "<th>";
echo $k;
echo "</th>";
}
}
echo "</thead>";
echo "<tbody>";
$i=0;
foreach($newOptions as $keys => $rows)
{
echo "<tr>";
echo "<td>";
echo $keys;
echo "</td>";
foreach($rows as $v)
{
echo "<td>";
echo " ". $i;
echo "</td>";
$i++;
echo "<td>";
echo $v;
echo "</td>";
}
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
?>
We can change structure of the array like this -
$Headers = array();
$headers[1] = "Leafy Life";
$headers[2] = "Aspley";
$headers[3] = "All Green";
$firstCloumnEntries = array();
$firstCloumnEntries[1] = "Callistemon1";
$firstCloumnEntries[2] = "Callistemon2";
$firstCloumnEntries[3] = "Acronychia";
$values = array();
$values[1] = array(); // this will have all values for first row;
$values[1][1] = "33";
$values[2] = array(); // this will have all values for second row;
$values[2][3] = "3.59";
$values[1] = array(); // this will have all values for third row;
$values[3][2] = "22.5";
Now while displaying - first add everything from all column "header" array.
Then for each row - use "firstCloumnEntries" array to get first value using index of the loop.
Write an inner loop to print corresponding row values. Before printing that value make use of isset().
Index "0" is purposely eliminated as we do not have any value in 0th column 0th row.
Index in the header array or in firstCloumnEntries array will help us to understand ID of the element inside it, e.g 1 is ID for "Leafy Life", 2 is for "Aspley" and so on.. using this we can add more headers with new IDs and more firstCloumnEntries with more IDs.
This will help in adding dynamic content and makes looping easy.
I don't understand why the result of the '$taille' array begin to the key [1] instead of key [0]? So it s displaying 3 results instead of 4 (occulting the first result)...
<?php
$req = $bdd->prepare('SELECT size FROM tailles_produits WHERE id_produit = ?');
$req->execute(array($_GET['id']));
$donnees = $req->fetch();
$numb_taille = array();
$taille = array();
$i = 0;
while($donnees = $req->fetch())
{
$i++;
$taille[$i] = $donnees['size'];
$numb_taille['total'] = $i;
}
$total = $numb_taille['total'];
echo '<pre>';
print_r ($taille);
echo '</pre>';
$req->closeCursor();
?>
Which gives
ARRAY
(
[1] => S
[2] => M
[3] => L
)
Instead of
ARRAY
(
[1] => XS
[2] => S
[3] => M
[4] => L
)
Can anyone help me with this pleas?
PHP arrays start with 0, so all you need to do is move your i++ down until after you're done using the data from that index
<?php
$req = $bdd->prepare('SELECT size FROM tailles_produits WHERE id_produit = ?');
$req->execute(array($_GET['id']));
$donnees = $req->fetch();
$numb_taille = array();
$taille = array();
$i = 0;
while($donnees = $req->fetch())
{
$taille[$i] = $donnees['size'];
$numb_taille['total'] = $i;
$i++; //iterate after your calculations are done
}
$total = $numb_taille['total'];
echo '<pre>';
print_r ($taille);
echo '</pre>';
$req->closeCursor();
?>
The problem is that you have an extra
$donnees = $req->fetch();
statement before the loop that fills in $taille. So the data from the first row is being fetched but not stored in the array.
It is because you increment $i before using it as a key for the new array item.
Do the increment at the end of your while loop.