Generate arrays dynamic - php

I have this part of code
$records = array();
$records["data"] = array();
foreach ($rows as $row) {//select from DB
$records["data"][] =array();//XXXX
foreach($this->t_data['columns'] as $column) {//columns for table
$records['data'][][]=$row[$column['name']];//THIS need to add into XXXX array
}
}
$records["draw"] = $sEcho;
return json_encode($records);
In try in many ways to add data into array. this code is from datatables.
This is wotking code, static
foreach ($tickete as $row) {
$records["data"][] = array(
'<input type="checkbox" name="idticket" value="' . $row['id'] . '">',
$row['name'],
$row['type'],
$row['state']
);
}
Format:
{"data":[
["ID1","Name","Type","State"],
["ID2","Name","Type","State"],
["ID3","Name","Type","State"],
["ID4","Name","Type","State"],
["ID5","Name","Type","State"]],"draw":2,"recordsTotal":50,"recordsFiltered":50}

Multiple solutions:
1) Temporary array, pushed at the end:
foreach ($rows as $row) {
$subArray = array();
foreach($this->t_data['columns'] as $column) {
$subArray[] = $row[$column['name']];
}
$records["data"][] = $subArray;
}
2) Using array index:
foreach ($rows as $row) {
$records["data"][] = array();
foreach($this->t_data['columns'] as $column) {
$records["data"][count($records["data"]) - 1][] = $row[$column['name']];
}
}
3) Reference to newly created array using index (useful only when you need to access it more often):
foreach ($rows as $row) {
$records["data"][] = array();
$subArray = &$records["data"][count($records["data"] - 1)];
foreach($this->t_data['columns'] as $column) {
$subArray[] = $row[$column['name']];
}
}

Related

create div from each item in tags column

My tags column is like this:
first row: sky - earth - sea
second row: iron - silver - gold
third row: apple - fruit - food
...and so on
Want to create a div from each item, like this:
<div class='tagdown'>sky</div>
<div class='tagdown'>earth</div>
$st = $db->query("select tags from posts");
$arr = array();
$items = "";
while ($row = $st->fetch()) {
array_push($arr, explode(' - ', $row['tags']));
}
foreach($arr as $item) {
$items .= "<div class='tagdown'>" . $item . "</div>\n";
}
echo $items;
Notice: Array to string conversion...
Another Try:
for ($i = 0; $i < count($arr); ++$i) {
$items .= "<div class='tagdown'>" . $arr[$i] . "</div>\n";
}
echo $items;
Notice: Array to string conversion...
Any help?
Dont push and again traverse your array. just print out data in while loop. Try following code:
$items = "";
while ($row = $st->fetch()) {
$arr = explode(' - ', $row['tags']);
$items .= "<div class='tagdown'>".implode("</div>\n<div class='tagdown'>",$arr)."</div>\n";
}
echo $items;
Try like shown below
Example :
<?php
$items = "";
$str = "sky-earth-sea";
$arr = explode("-", $str);
$count = count($arr);
for($i = 0; $i < $count; $i++) {
$items .= "<div class='tagdown'>".$arr[$i]."</div></br>";
}
echo $items;
?>
explode() returns an array and you are pushing an array into an other array
its making 1 2D array you can check thar using print_r($arr);
use this
while ($row = $st->fetch()) {
$tag=explode('-', $row['tags'];
foreach($tag as $t){
array_push($arr,$t ));
}
}
You can also use fetch associative if using mysqli_connect
while ($row = $result->fetch_assoc()) {
array_push($arr, explode(' - ', $row['tags']));
}
foreach($arr as $a) {
foreach($a as $v){
$items .= "<div class='tagdown'>" . $v . "</div>\n";
}
}
echo $items;
-------------- OR -------------
$arr = array();
$items = "";
while ($row = $result->fetch_assoc()) {
$tag = explode(' - ', $row['tags']);
foreach($tag as $v){
$items .= "<div class='tagdown'>" . $v . "</div>\n";
}
}
echo $items;

Trying to create associative array but keep getting numeric

I am trying to create an associate array like this
while($row = $result1->fetch_assoc()) {
$user = $row['first_name'] ."_" . $row['last_name'];
$userholder[$user] = $row['choice'];
$event = $row['event_name'] . "_" . $row['event_location'] . "_" . $row['even_date'];
$consolidateEvents[$event] = $userholder;
}
but my $consolidateEvents array is numeric. I cannot see what I am doing wrong. Why am I not getting $event as the key for my array?
Try this code to correct your output,
function custom_function($input_array){
$output_array = array();
foreach ($input_array as $key => $value) {
foreach ($v as $k => $v) {
$output_array[$key][$k] = $v;
}
}
return $output_array;
}
Give it a try, this will work

Simple HTML Dom - parse only few columns from original table

I want to copy some table to my website, but only with few specific columns
Here is my code
<?php
require('simple_html_dom.php');
$html = file_get_html('http://pomorskifutbol.pl/liga.php?id=970');
$table = $html->find('table', 0);
$rowData = array();
foreach($table->find('tr') as $row) {
// initialize array to store the cell data from each row
$flight = array();
foreach($row->find('td') as $cell) {
// push the cell's text to the array
$flight[] = $cell->plaintext;
}
$rowData[] = $flight;
}
echo '<table>';
foreach ($rowData as $row => $tr) {
echo '<tr>';
foreach ($tr as $td)
echo '<td>' . $td .'</td>';
echo '</tr>';
}
echo '</table>';
?>
whole table
And this prints whole table, I want to get only few columns, for example only "M.", "Drużyna", "M", "PKT"
How extract only this columns from this table?
You can change the entry:
foreach($row->find('td') as $cell) {
to
foreach($row->find('td') as $columnNumber => $cell) {
and make an if before the filling of the $flights array, e.g
//somewhere in code
$columnNumbers = [ 0, 2, 3,4, 7];
// int the foreach loop
if ( in_array( $columnNumber, $columnNumbers ) ) {
$flight[] = $cell->plaintext;
}
PS. Powodzenia :)

Split flat array into 4 transposed subarrays and print as html table [duplicate]

This question already has answers here:
Chunk and transpose a flat array into rows with a specific number of columns
(3 answers)
Closed 10 months ago.
I want to add foreach entry sequence wise for example
suppose my array like this
$arr = array('111','222','333','444','555','666','777','888','999'..so on);
Now using foreach, I want to enter print the array data like this:
<div>
<p>111</p>
<p>555</p>
<p>999</p>
</div>
<div>
<p>222</p>
<p>666</p>
</div>
<div>
<p>333</p>
<p>777</p>
</div>
<div>
<p>444</p>
<p>888</p>
</div>
Here is execution how to do it.
First create split array, which groups necessary elements into 4 groups. Then in second foreach, each is formatted. This is an example, may not be very effective in large data arrays.
$arr = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
$split = [];
foreach ($arr as $k => $v) {
$split[$k % 4][] = $v;
}
$out = '';
foreach ($split as $row) {
$out .= '<div>';
foreach ($row as $e) {
$out .= '<p>' . $e . '</p>';
}
$out .= '</div>';
}
Another way you could do it, similar to tilz0R
<?php $rowArray = array();
$counter = 1;
foreach ($arr as $item){
$rowArray[$counter][] = $item;
if ($counter == 3){$counter = 1;}else{$counter++;}
}
foreach ($rowArray as $row)
{
?><div>
<?php foreach ($row as $item)
{
?><p><?= $item?></p>
<?php }?></div><?php
};?>
You can use array_walk:
const NB_ROWS = 4;
for ($row = 0; $row < NB_ROWS; $row++) {
echo "<div>\n";
array_walk($arr, function($item, $key, $row) { if($key % NB_ROWS == $row) echo "<p>$item</p>\n"; }, $row);
echo "</div>\n";
}
Or to be clearer:
Define a function that will print only elements of the given row:
function printRow($item, $key, $row)
{
if($key % 4 == $row) {
echo "<p>$item</p>\n";
}
}
Then call it once for each row:
for ($row = 0; $row < 4; $row++) {
echo "<div>\n";
array_walk($arr, 'printRow', $row);
echo "</div>\n";
}

Calculate max, min, and average for every column in a 2D array

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>';

Categories