PHP Multidimensional Arrays , display data in a tabular form -
when echo array , result :
$items = array( [147] => array([itemname] => array([0]=>white snack [1]=>dark cookie) [itemcode] => array([0]=>it-ws [1]=>it-dc ) ) [256] => array([itemname] => array([0]=>soft sandwiches [1]=>hard drinks) [itemcode] => array([0]=>it-ss [1]=>it-hd ) ))
now need display following result in tabular form , indexes 147 , 256 , pass them separate foreach loop correct index value.
-----------147---------------
name ----------------------------------- code
white snack --------------------------- ws
dark cookie --------------------------- dc
-----------256---------------
name ----------------------------------- code
soft sandwiches ---------------------- ss
hard drinks ---------------------------- hd
am not able achieve this. please help.
$itemindexes = array(147,256); foreach($itemindexes $itemmainindex) { //further code here , //here send $itemmainindex $items array //and corresponding index value , display accordingly. }
the structure of array didn't go structure of display, made new array different structure
$prods = array(); foreach ($items $key => $group){ foreach ($group $attr => $values){ foreach ($values $key2 => $value){ $prods[$key][$key2][$attr] = $value; } } } var_dump($prods);
output:
array( [147] => array( [0] => array( [itemname] => white snack [itemcode] => it-ws ) [1] => array( [itemname] => dark cookie [itemcode] => it-dc ) ) [256] => array [0] => array( [itemname] => soft sandwiches [itemcode] => it-ss ) [1] => array( [itemname] => hard drinks [itemcode] => it-hd ) ) )
with that, looped through make table:
$table = '<table>'; foreach ($prods $key => $group){ $table .= '<tr><td colspan="2">'.$key.'</td></tr>'; $table .= '<tr><td>name</td><td>code</td></tr>'; foreach ($group $key2 => $values){ $table .= '<tr>'; foreach ($values $attr => $value){ if ($attr == 'itemcode'){ $parts = explode('-', $value); $table .= '<td>'.$parts[1].'</td>'; } else { $table .= '<td>'.$value.'</td>'; } $prods[$key][$key2][$attr] = $value; } $table .= '</tr>'; } } $table .= '</table>';
with styling, can display more or less showed. in array posted, there parenthesis out of place, structure of original array used was:
$items = array(147 => array('itemname' => array(0=>'white snack', 1=>'dark cookie'), 'itemcode' => array(0=>'it-ws', 1=>'it-dc')), 256 => array('itemname' => array(0=>'soft sandwiches', 1=>'hard drinks'), 'itemcode' => array(0=>'it-ss', 1=>'it-hd')));
Comments
Post a Comment