I want to create an assosiative array which it will have as one of its elements an other array (not assosiative)
$temp= array(
'elem1' => $data1,
'elem2' => $data2,
'elem3' => $data5,
);
$data2 is a simple array already constructed. However, I cannot find the right syntax for doing that. By applying the classic following I cannot get the values of elem2.
while ($element=each($temp))
{
echo $element['key'];
echo " - ";
echo $element['value'];
echo "<br/>";
}
It's not quite clear from your question, but depending on the structure of $data2, printing its values separated by commas may suffice:
foreach ($temp as $key => $value) {
echo $key, ' - ';
if (is_array($value)) {
echo implode(',', $value);
}
else {
echo $value;
}
echo '<br/>';
}
try this
$data = ['elem1' => '1', 'elem2' => ['red','blue','orange' ],'elem3' => '3'];
$tmp ='';
foreach ($data as $key => $value ) {
$tmp .= $key.' - ' ;
if (is_array($value)) {
$tmp.= implode(',', $value).' ';
}else {
$tmp .= $value. ' ';
}
}
echo json_encode($tmp);
You can echo the values in this way:
foreach($temp as $key => $value) {
echo $key;
echo " - ";
if(is_array($value)) {
echo "Array: # ";
foreach($value as $value_key => $value_value) {
echo $value_key." - ".$value_value." # ";
}
} else {
echo $value;
}
echo "<br/>";
}
Codepad Example
I 'm trying to create a comparison table from an array like this:
Array ( [0] => Array ( [name] => Sony X852
[4G] => 1
[Backlighting] => 0
)
[1] => Array ( [name] => Nokia 12hb
[4G] => 0 // have trouble with this element
[Backlighting] => 0
)
[2] => Array ( [name] => Asus 23yh
[4G] => 1
[Backlighting] => 0
)
)
$table = "";
$table .= "<table><tbody>";
foreach($array as $key=>$val)
{
$table .= "<tr>";
foreach($val as $k=>$v)
{
if($k == "name")
{
$table .= "<td>$v</td>";
}
else if($v > 0)
{
$table .= "<td>$k</td><td>$v</td>";
}
}
$table .= "</tr>";
}
$table .= "</tbody></table>";
print $table;
Here's my expected result:
<table>
<tbody>
<tr><td>Sony X852</td><td>4G</td><td>1</td></tr>
<tr><td>Nokia 12hb</td><td>4G</td><td>0</td></tr> // don't skip the 4G td for this phone
<tr><td>Asus 23yh</td><td>4G</td><td>1</td></tr>
</tbody>
</table>
But the output I'm getting from the code above is this:
<table>
<tbody>
<tr><td>Sony X852</td><td>4G</td><td>1</td></tr>
<tr><td>Nokia 12hb</td></tr>
<tr><td>Asus 23yh</td><td>4G</td><td>1</td></tr>
</tbody>
</table>
1 and 0 here indicate whether a product has that feature. How can I skip over an element only if the same key/value pairs in the other rows are 0? For example, all of the three products don't have Backlighting features, so I use if($v > 0) to exclude the whole row of Backlighting, but I want to keep any 0 element like Nokia 12hb's 4G because the other phones contain that feature.
Expanding from the comment from #Barmar
$features = array();
foreach ($array as $row) {
foreach ($row as $key => $value) {
if ($key != 'name' && $value > 0) {
$features[] = $key;
}
}
}
foreach ($array as $row) {
$table .= "<tr><td>{$row['name']}</td>";
foreach ($row as $key => $value) {
if ($key != 'name' && in_array($key, $features)) {
$table .= "<td>{$key}</td><td>{$value}</td>";
}
}
$table .= "</tr>
}
First make a list of all the features that have non-zero in some element:
$features = array('name' => true);
foreach ($array as $item) {
foreach ($item as $feature => $val) {
if (!isset($features[$feature]) && $val > 0) {
$features[$feature] = true;
}
}
}
Then use this in your output loop:
foreach($array as $key=>$val)
{
$table .= "<tr>";
foreach($val as $k=>$v)
{
if($k == "name")
{
$table .= "<td>$v</td>";
}
elseif(isset($features[$k]))
{
$table .= "<td>$k</td><td>$v</td>";
}
}
$table .= "</tr>";
}
The answer appears simple. The value for $v is never greater than zero in the second Nokia array! So..your else if($v > 0){.. never fires!
The solution here would be to check for $v==0 || $v < 0, then print the desired output as well. Right now you aren't doing that so your output ignores when $v is zero or negative.
I'm calculating the average,min,max for each column.
The 16th column value is coming wrong for max and min. Average is working perfectly fine, but wrong only for the last column with large arrays -- I also get a notice error.
My code:
mysql_connect("localhost", "root", "") or
die("Could not connect: " . mysql_error());
mysql_select_db("db");
$qry = mysql_query("select blob_field from table where id=1");
$arr = mysql_fetch_row($qry) ;
$rt = explode("\n",$arr[0]);
$header_arr1 = explode(',',$rt[0]);
$header1 = array();
$channels = count($header_arr1)-2 ;
$header1[] = join(',', array_slice($header_arr1, 2));
//Only Header
$arr_values = array_values($rt);
$array_slice = array_slice($arr_values, 1);
echo "<pre>";
//print_r($array_slice);
$result_array = array();
for($i=0;$i<count($array_slice);$i++)
{
//echo $i;
$result_array[] = join(',',array_slice(explode(',', $array_slice[$i]), 2));
}
//print_r($result_array);
//$array_combined = array_merge($header1,$result_array);
$token = array( 'Average', 'Max', 'Min');
foreach($result_array as $key=>$val)
{
$res_arr[] = explode(",",$val);
}
$avArray = array();
$res_arr= array(
0=>array(1,2,3,6,7,8,9,11,33,44,55,66,77,88,16,18),
1=>array(17,52,38,666,79,8,9,15,33,44,55,66,76,88,16,18),
2=>array(17,562,538,7666,579,688,9,15,933,44,55,660,76,808,106,108),
);
foreach ($res_arr as $k=>$subArray)
{
foreach ($subArray as $id=>$value)
{
//print_r($id);
$avArray[$id] += $value/count($res_arr); //Notice: Undefined offset: 3
}
}
$token = array( 'Average', 'Max', 'Min');
$num = $avArray;
$tc=16;
?>
<table border="1" style="border-collapse: collapse;">
<thead>
<tr>
<th>Channels</th>
<?php for($j=0;$j<=$tc-1;$j++):?>
<th>CH<?= $j+1;?></th>
<?php endfor;?>
</tr>
</thead>
<tbody>
<?php
echo "<tr><td>Average</td>";
for($i=0; $i<=$tc-1;$i++)
{
echo "<td>" .round($num[$i],2). "</td>";
}
echo "<tr><td>Max</td>";
$arr_max = array();
foreach($res_arr as $subArray)
{
foreach($subArray as $k=>$v) {
$arr_max[$k][] = $v;
}
}
$max_array = array_map('max', $arr_max);
for($i=0; $i<=$tc-1;$i++)
{
echo "<td>" .$max_array[$i]. "</td>";
}
echo "<tr><td>Min</td>";
$arr_min = array();
foreach($res_arr as $subArray)
{
foreach($subArray as $k=>$v1) {
$arr_min[$k][] = $v1;
}
}
$min_array = array_map('min', $arr_min);
for($g=0; $g<= $tc-1;$g++)
{
echo "<td>" .$min_array[$g]. "</td>";
}
?>
</tbody>
</table>
See inline comments for explanation.
$avArray = array();
$res_arr= array(
0=>array(1,2,3,6,7,8,9,11,33,44,55,66,77,88,16,18),
1=>array(17,52,38,666,79,8,9,15,33,44,55,66,76,88,16,18),
2=>array(17,562,538,7666,579,688,9,15,933,44,55,660,76,808,106,108),
);
/*
foreach ($res_arr as $k=>$subArray){
foreach ($subArray as $id=>$value){
// this causes "Notice: Undefined offset: 0...15" because you can't add to an undeclared value
$avArray[$id] += $value/count($res_arr);
}
}
*/
$res_count=count($res_arr); // declare this outside of the loop for efficiency
foreach ($res_arr as $k=>$subArray){
foreach ($subArray as $id=>$value){
if($k==0){
$avArray[$id]=$value; // declare first round of values
}else{
$avArray[$id]+=$value; // add to existing values
if($k==2){
$avArray[$id]=$avArray[$id]/$res_count; // only divide on the last iteration
}
}
}
}
print_r($avArray);
No matter how you want to present it, you are going to have to loop over the data set more than one. Once to calculate and once to display.
Here is another snippet: (Demo)
$array = [
[1,2,3,6,7,8,9,11,33,44,55,66,77,88,16,18],
[17,52,38,666,79,8,9,15,33,44,55,66,76,88,16,18],
[17,562,538,7666,579,688,9,15,933,44,55,660,76,808,106,108],
];
$count = count($array);
$mins = [];
$maxs = [];
$avgs = [];
foreach ($array as $i => $row) {
foreach ($row as $col => $value) {
$ch = $col + 1;
if (!$i) {
$mins[$ch] = $value;
$maxs[$ch] = $value;
$avgs[$ch] = $value;
} else {
if ($value < $mins[$ch]) {
$mins[$ch] = $value;
}
if ($value > $maxs[$ch]) {
$maxs[$ch] = $value;
}
$avgs[$ch] += $value;
if ($i === $count - 1) {
$avgs[$ch] = number_format($avgs[$ch] / $count, 2);
}
}
}
}
echo '<table border=1>';
printf(
'<tr><th>Channels</th><th>CH%s</th></tr>',
implode('</th><th>CH', array_keys($avgs))
);
printf(
'<tr><th>Average</th><td>%s</td></tr>',
implode('</td><td>', $avgs)
);
printf(
'<tr><th>Max</th><th>%s</td></tr>',
implode('</td><td>', $maxs)
);
printf(
'<tr><th>Min</th><td>%s</td></tr>',
implode('</td><td>', $mins)
);
echo '</table>';
Im trying to calculate a subtotal and a total from a series of values stored in an array returned from a mysql database.
this i what i have thusfar
while($row = mysql_fetch_array($cart)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
$contents = unserialize($row['contents']);
foreach( $contents as $key => $value){
if($key == "price"){$subtotal = $subtotal+$value;}
echo "$key : $value <br />";
}
echo "<br><br><br>";
}
echo "<font color=red>SubTotal $subtotal</font>";
$contents contains an array [name] => super [price] => 65.87 [quantity] => 25
So i need to multiply the price by quantity, and then take that subtotal (per item) and add it in total after the loop
foreach( $contents as $key => $value)
{
if($key == "price") $total = $total+$value;
if($key == "name")
{
if(!isset($subtotal[$key])) $subtotal[$key] = 0;
$subtotal[$key] = $subtotal[$key] + $value;
}
}
Then you have total price in $total and for each individual item in $subtotal array
I'm not sure what you mean for total and subtotal. I assume that subtotal is the price of an item times his quantity.
For Total I assume you intend the subtotal you print in red.
Your code become:
$total=0;
while($row = mysql_fetch_array($cart)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
$contents = unserialize($row['contents']);
$contents['subtotal'] = $contents['price']*$contents['quantity'];
foreach($contents as $key => $value){echo "$key : $value <br />"; }
$total +=$content['subtotal'];
}
echo "<font color=red>Total: $total</font>";
If the formatting is not mandatory I would use a slight different solution
for formatting the output. (you should check the printf format string placeholder syntax)
$billLine = "%s (%0.2f x %d): %0.2f<br /><br /><br />";
$total=0;
while($row = mysql_fetch_array($cart)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
$contents = unserialize($row['contents']);
$subtotal = $contents['price']*$contents['quantity'];
printf($billLine, $contents['name'],
$contents['quantity'],
$contents['price'],
$subtotal);
$total +=$subtotal;
}
echo "<font color=red>Total: $total</font>";