PHP While loop array - php

Any help is appreciated.
I have an array that is forfetch like this. The reason is to brake down a product in individual arrays. However I can not figure out what statement to put in the while loop so i can loop through each array in $row. initially the statement should be
while ($row = mysql_fetch_assoc($result))
however this was already done to be able to sort the array.
$sorted = array_orderby($newarray, 'volume', SORT_DESC, 'edition', SORT_ASC);
foreach($sorted as $row)
{
while( ??????? )
{
$row = build_items($row);
$template->assign_block_vars('featured_items', array(
'ID' => $row['id'],
'IMAGE' => $row['pict_url'],
'TITLE' => $row['title'],
'SUBTITLE' => $row['subtitle'],
'BUY_NOW' => ($difference < 0) ? '' : $row['buy_now'],
'B_BOLD' => ($row['bold'] == 'y')
));
$k++;
$feat_items = true;
}
}
Just found the answer. Sorry guys im new at PHP.
foreach($sorted AS $row) {
$row = build_items($row);
// time left till the end of this auction
$s_difference = time() - $row['starts'];
$difference = $row['ends'] - time();
$bgcolour = ($k % 2) ? 'bgcolor="#FFFEEE"' : '';
$template->assign_block_vars('featured_items', array(
'ID' => $row['id'],
'IMAGE' => $row['pict_url'],
'TITLE' => $row['title'],
'SUBTITLE' => $row['subtitle'],
'BUY_NOW' => ($difference < 0) ? '' : $row['buy_now'],
'BID' => $row['current_bid'],
'BIDFORM' => $system->print_money($row['current_bid']),
'TIMELEFT' => FormatTimeLeft($difference),
'NUMBIDS' => $row['num_bids'],
'B_BOLD' => ($row['bold'] == 'y')
));
$k++;
$feat_items = true;
}

foreach($sorted AS $rows) {
foreach($rows AS $row) {
...
}
}
or with keys/indices
foreach($sorted AS $key => $rows) {
foreach($rows AS $index => $row) {

Yes.., we can use foreach to print all the values in an array.
Example: I have an array called "data" (SQLITE dynamic data). I want to print all the values which are there on "data" array.
By using following sample code we can print the values in a table format.
foreach ($data as $item) {
$date = $item['date'];
$url = $item['url'];
$name = $item['name'];
echo"
<tr>
<td>$date</td>
<td>$name</td>
<td>$url</td>
</tr>
";
}
Please let me know if i did any mistakes here, sorry for my bad English.

Related

php dynamic table from muldimentional array

can you give me idea how to implement this idea for "dynamic" html table.
I have an array
$arr = array(
array(
'label' => 'First name',
'data' => array(
array('fname' => 'John'),
array('fname' => 'Ralph'),
),
),
array(
'label' => 'Last name',
'data' => array(
array('lname' => 'Doe'),
array('lname' => 'Loren'),
),
),
array(
'label' => 'Description',
'data' => array(
array('description' => 'Something bout John'),
array('description' => 'Something about Ralph'),
),
),
);
Now from the keys 'label' im creating the table columns
---------------------------------------
|First Name | Last Name | Description |
---------------------------------------
The problem is how to put 'fname' keys in the first column, 'lname' in the second and 'description' in the third.
With this part of code im trying to put the data in all columns
private function tableBody()
{
$data = $this->data;
$table = '<tbody>';
foreach($data as $key => $value){
foreach($value['data'] as $k => $v){
$table .= '<tr>';
foreach($v as $col => $name){
$table .= '<td>' . $name . '</td>';
}
$table .= '</tr>';
}
}
$table .= '</tbody>';
return $table;
}
Also my idea is not to hard code array keys for multiple usage(except label and data).
First I would remap the data to process it in loops.
$labels = [];
$rows = [];
foreach($arr as $column) {
$label = $column['label'];
$labels[] = $label;
foreach($column['data'] as $key => $value) {
$rows[$label][] = $value;
}
}
Now print out the labels with the headline.
echo "<table>\n";
echo "<tr>";
foreach($labels as $label) echo "<th>{$label}</th>";
echo "</tr>\n";
Iterate through the rows and create the HTML.
$labelCount = count($labels);
$rowCount = count($rows[$labels[0]]);
while($rowCount) {
echo "<tr>";
for ($i = 0; $i < $labelCount; $i++) {
$current = array_shift($rows[$labels[$i]]);
$value = reset($current);
echo "<td>{$value}</td>";
}
echo "</tr>\n";
$rowCount--;
}
echo "</table>\n";
This gives a table like below
<table>
<tr><th>First name</th><th>Last name</th><th>Description</th></tr>
<tr><td>John</td><td>Doe</td><td>Something bout John</td></tr>
<tr><td>Ralph</td><td>Loren</td><td>Something about Ralph</td></tr>
</table>
You need to manipulate the initial array to reduce it to something more manageable. You could brute force your way like so:
function reduce($data) {
$ret = [];
foreach ($data as $d1) {
// column header could have been fetched here
foreach ($d1 as $k2 => $d2) {
// keeping track of what label we need
$key = '';
// keeping the values together
$child = [];
// discarding non arrays
if (is_array($d2)) {
foreach ($d2 as $d3) {
// identifier fetch from this level
foreach ($d3 as $k4 => $d4) {
$key = $k4;
$child[] = $d4;
}
}
}
// assigning back to the main array only if we have something
if (!empty($child)) {
$ret[$key] = $child;
}
}
}
return $ret;
}
That will return the following:
Array
(
[fname] => Array
(
[0] => John
[1] => Ralph
)
[lname] => Array
(
[0] => Doe
[1] => Loren
)
[description] => Array
(
[0] => Something bout John
[1] => Something about Ralph
)
)

Merge duplicate values from array in Json Formate

I am fetching data from location MySql table as structure is below
in my PHP code
I need send Json output in response as below (Table data may not be same as below json data but the format is same)
http://jsoneditoronline.org/?id=7c5600712df6f9ec1f8fbb8a13aba3de
Tried to do the following in the code to convert the array that i fetch from the table but however am unable to get it in the right format
$sql = "SELECT * FROM mobile_user_regions";
$stmt = $this->db->prepare($sql);
$stmt->execute();
$resCArray = $stmt->fetchAll(PDO::FETCH_ASSOC);
$ress = array();
foreach ($resCArray as $key => $value) {
$ress['regions'][] = array(array(
'name' => $value['region'],
'location' => array(
array(
'name' => $value['location'],
'store' => array(
'store_details' => $value['store_details'],
'store_phone' => $value['store_phone'],
'store_email' => $value['store_email'],
'store_latitude' => $value['store_latitude'],
'store_longitude' => $value['store_longitude']
)
)
)
)
);
Output: that i am getting is
**http://jsoneditoronline.org/?id=4d4a75177350e254ceee7238af13f2f7**
$regionArray = $xyzObject->getRegion();
if (!empty($regionArray) && isset($regionArray)) {
$i = 0;
$locationData = array();
foreach ($regionArray as $key => $value) {
$locationData['regions'][$i]['name'] = $value['region'];
$locationArray = $xyzObject->getLocation($value['region']);
$locationData['regions'][$i]['locations'] = $locationArray;
$i++;
}
$j = 0;
foreach ($locationData['regions'] as $key => $regions) {
$k = 0;
foreach ($regions['locations'] as $key1 => $locations) {
$storeArray = $xyzObject->getStore($locations['name']);
$locationData['regions'][$j]['locations'][$k]['stores'] = $storeArray;
$k++;
}
$j++;
}
echo json_encode($locationData);

How to display the value of array as string or text not as index value

I have two table one for sections where each section has many questions when i echo i got the section text but the questions as index value 0 1 2
<?php
$result = mysql_query($query);
if ($result) {
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[($row['SECTION_NAME'])][][($row['QUES_TEXT'])][] = array(
'SECTION' => $row['SECTION_NAME'],
'QUESTION' => $row['QUES_TEXT']
);
}
foreach ($data as $SECTION => $QUESTIONS) {
echo '<h2>',htmlentities($SECTION),'</h2>';
foreach ($QUESTIONS as $QUESTIONS_TEXT => $TEXT) {
echo '<h2>',($QUESTIONS_TEXT),'</h2>';
}
}
}
?>
You are creating extra nested arrays and also the parens are unneeded:
$data[$row['SECTION_NAME']][][$row['QUES_TEXT']][] = array(
'SECTION' => $row['SECTION_NAME'],
'QUESTION' => $row['QUES_TEXT']
);
Should be:
if (empty($data[$row['SECTION_NAME']]) {
$data[$row['SECTION_NAME']] = array();
}
$data[$row['SECTION_NAME']][$row['QUES_TEXT']] = array(
'SECTION' => $row['SECTION_NAME'],
'QUESTION' => $row['QUES_TEXT']
);
Also please see the comments to your original question, this is no longer a safe way to use MySQL from PHP.

Unite into one array based array from explode string in php

I have a lot of array based explode a string like this :
$size = explode(",", $row->SIZE);
$coil_no = explode(",", $row->COIL_NO);
$net = explode(",", $row->NET);
$gross = explode(",", $row->GROSS);
$contract_no = explode(",", $row->CONTRACT_NO);
$location = explode(",", $row->LOCATION);
How can I unite those array into one multidimensional array ?
I have try like this :
foreach ($size as $value) {
foreach ($coil_no as $coil) {
$detail[] = array(
"coil_no" => $coil,
"size" => $value
);
}
}
you know the result the looping is loop weird,
I need more elegant array, like
foreach ($unite_array as $row) :
echo "<tr> $row->size </tr>" ;
endforeach;
What the best way to unite those array ?
You can write your own function which does the grouping on keys as required, see example below:
function array_group(){
if(func_num_args() > 0) {
$params = func_get_args();
$result = array();
foreach($params as $key => $param) {
foreach($param['values'] as $k => $value) {
$result[$k][$param['alias']] = $value;
}
}
return $result;
}
return false;
}
$rows = array_group(
array('alias' => 'size', 'values' => array(1,2,3,4,5)),
array('alias' => 'coil_no', 'values' => array(6,7,8,9,10)),
array('alias' => 'net', 'values' => array(11,12,13,14,15)),
array('alias' => 'gross', 'values' => array(16,17,18,19,20)),
array('alias' => 'contract_no', 'values' => array(21,22,23,24,25)),
array('alias' => 'location', 'values' => array(26,27,28,29,30))
);
print_r($rows);
And you can access it like:
foreach ($rows as $row) :
echo "<tr> {$row['size']} </tr>" ;
endforeach;

Assigning array values to subarray of another array

I have an array in $xml->channel->item which outputs correctly if I run:
foreach ($xml->channel->item as $entry){
echo $entry->title;
echo $entry->category;
echo $entry->pubDate;
}
Now, I am struggling to make this array work with the following form, which outputs a formatted table:
$rows = array(
'row[0]' => array('title' => 'Test Title','category' => 'Computer', 'date' => 'test date'),
'row[1]' => array('title' => 'Test Title 2','category' => 'Chemical', 'date' => 'test date'),
);
$form['table'] = array(
'#type' => 'tableselect',
'#header' => $header,
'#options' => $rows,
);
I tried this code, but it didn't work:
$i=0;
foreach ($xml->channel->item as $rows){
row[$i][title] = $rows->title;
row[$i][category] = $rows->category;
row[$i][date] = $rows->pubDate;
$i=++;
}
SOLUTION:
Copying the solution I figured out from the comment below to the post body:
$rows = array();
foreach ($xml->channel->item as $entry) {
$row['title'] = $entry->title;
$row['category'] = $entry->category;
$row['date'] = $entry->pubDate;
array_push($rows, $row);
}
Finally figured out. I hope this will save others hitting the similar task:
$rows = array();
foreach ($xml->channel->item as $entry) {
$row['title'] = $entry->title;
$row['category'] = $entry->category;
$row['date'] = $entry->pubDate;
array_push($rows, $row);
}

Categories