How I echo this kind of array in php? - php

I do have an array something like below:
[images] => Array
(
[0] => Array
(
[id] => 1
[path] => ../images/properties/1/1447053991.jpg
)
[1] => Array
(
[id] => 3
[path] => ../images/properties/1/1447054231.jpg
)
[2] => Array
(
[id] => 4
[path] => ../images/properties/1/1447054666.jpg
)
[3] => Array
(
[id] => 17
[path] => ../images/properties/1/1447141341.jpg
)
)
When I need to echo this array, I want to add different HTML for first key of this array and also different HTML for other keys.
This is how I tried it:
foreach($property['images'] as $image) {
//echo '<pre>',print_r($image).'</pre>';
if ($image['id'] != '') {
$html .= " <a href='".$image['path']."' class='image-wrap' title='' rel='prettyPhoto'>\n";
$html .= " <img src='".$image['path']."' alt=''/>\n";
$html .= " <span class='zoom-icon'></span>\n";
$html .= " </a>\n";
} else {
$html .= " <a href='".$image['path']."' title='1' rel='prettyPhoto[group]'></a>\n";
}
}
But its not working for me. Hope somebody may help me out.

If I am not wrong your foreach is printing values as expected and you want the first index to print out something different then others..
foreach($property['images'] as $index => $image) {
//echo '<pre>',print_r($image).'</pre>';
if ($index == 0) {
// do stuff for the first index
} else {
// do stuff for other indexes
}
}

since you want to display first image as image and the rest in anchor tag try this.use a counter to identify first and the rest.there can be two cases.
case 1: when your index does not start with 0.
$property=array('images' => Array
(
'0' => Array
(
'id' => 1,
'path' => '../images/properties/1/1447053991.jpg'
),
'1' => Array
(
'id' => 3,
'path' =>'../images/properties/1/1447054231.jpg'
)
)
);
$html="";
$counter=0;
foreach($property['images'] as $image) {
if ($image['id'] != '') {
if($counter == 0){
$html .= " <img src='".$image['path']."' alt=''/>\n";
$counter++;
}else{
$html .= " <a href='".$image['path']."' class='image-wrap' title='' rel='prettyPhoto'>".$image['id']."\n";
$html .= " <span class='zoom-icon'></span>\n";
$html .= " </a>\n";
}
} else {
$html .= " <a href='".$image['path']."' title='1' rel='prettyPhoto'group''></a>\n";
}
}
echo $html;
?>
case 2: when index starts from 0.
foreach($property['images'] as $key=>$image) {
if ($image['id'] != '') {
if($key == 0){
$html .= " <img src='".$image['path']."' alt=''/>\n";
}else{
$html .= " <a href='".$image['path']."' class='image-wrap' title='' rel='prettyPhoto'>".$image['id']."\n";
$html .= " <span class='zoom-icon'></span>\n";
$html .= " </a>\n";
}
} else {
$html .= " <a href='".$image['path']."' title='1' rel='prettyPhoto'group''></a>\n";
}
}

Related

How to make a response data in array for Morris

I want to create a data array from a return value of mysql. The raw data from mysql is :
$chart=Array (
[bd] => Array (
[Eid] => 59100
[Mona] => 156050
[Nai] => 27750
[Nana] => 90680
[Pinya] => 9400
[Pok] => 43900
[Tunk] => 48600
[VEE] => 26800
)
[cp] => Array (
[Eid] => 23650
[Mona] => 86760
[Nai] => 54160
[Nana] => 125300
[Pinya] => 63960
[Pok] => 59800
[Tunk] => 111260
[VEE] => 125460
)
)
I want the final result comes in this format:
{
hotel: 'BD',
Eid:59100,
Mona:156050,
Nai:27750,
Nana:90680,
Pinya:9400,
Pok:43900,
Tunk:48600,
VEE:26800,
}...
So, I write :
foreach($chart as $hotel=>$rep){
echo "{hotel:$hotel, $rep},";
}
And the result is:
{hotel:bd, Array},{hotel:cp, Array},{hotel:cs, Array},{hotel:km, Array}{hotel:nk, Array},
It is similar to what I want but how can I extract the Array into the format shown above?
This Code Works .
$finalArray = array();
$i = 0;
foreach($chart as $hotel=>$rep) {
$finalArray[$i] = "{<br>hotel: $hotel,<br>";
foreach($rep as $key=>$val) {
$finalArray[$i] .= "$key:$val,<br>";
}
$finalArray[$i] .= "}<br>";
$i++;
}
$finalString = implode(",",$finalArray);
echo $finalString;
Would something like this work?
// set empty string
$sOutput = '';
// loop over each char data using its key as the hotel id/ref
foreach ($chart as $sHotelID => $aHotelData) {
// if there is already output add a comma to the end
if($sOutput != '') $sOutput .= ",";
// add the opening brace and hotel info
$sOutput .= "{hotel:".$sHotelID.",";
// set empty string
$sTempOutput = '';
// loop over each hotel data entry storing into tempOutput
foreach ($aHotelData as $sKey => $sValue) {
if($sTempOutput != '') $sTempOutput .= ",";
$sTempOutput .= $sKey.":".$sValue;
}
// assign the tempoutput to the main output
$sOutput .= $sTempOutput."}";
}
var_export($sOutput);
This gives me:
{Eid:59100,Mona:156050,Nai:27750,Nana:90680,Pinya:9400,Pok:43900,Tunk:48600,VEE:26800},
{Eid:23650,Mona:86760,Nai:54160,Nana:125300,Pinya:63960,Pok:59800,Tunk:111260,VEE:125460}

Echo multidimensional array in a html table

I am having a multidimensional array with same values like this,
[documents] => Array
(
[0] => Array
(
[doc_id] => 3
[doc_type] => driving_licence
[expiry_date] => 2015-11-26
[added_date] => 2015-11-16
)
[1] => Array
(
[doc_id] => 3
[doc_type] => driving_licence
[expiry_date] => 2015-11-26
[added_date] => 2015-11-16
)
)
So now I need to echo this array in a html table with single <tr>.
This is how I tried it :
foreach ($userData as $key => $value) {
$i=0;
foreach ($value['documents'] as $k => $v) {
$i++;
$html = "<tr>\n";
$html .= " <td class='center'>{$i}</td>";
$html .= " <td>{$v['doc_type']}</td>";
$html .= " <td>{$v['expiry_date']}</td>";
$html .= " <td>{$v['added_date']}</td>";
$html .= "</tr>\n";
echo $html;
}
}
But its repeating table <tr> with same values.
Can anybody tell me how to avoid this?
Thank you.
As requested, here is an example for you.
$userData = $input = array_map("unserialize", array_unique(array_map("serialize", $userData)));
foreach ($userData as $key => $value) {
$i=0;
foreach ($value['documents'] as $k => $v) {
$i++;
$html = "<tr>\n";
$html .= " <td class='center'>{$i}</td>";
$html .= " <td>{$v['doc_type']}</td>";
$html .= " <td>{$v['expiry_date']}</td>";
$html .= " <td>{$v['added_date']}</td>";
$html .= "</tr>\n";
echo $html;
}
}
That will give you a table with 1 <tr> row.
this is the way i would do what you are trying to do:
$movies = array
(
array('Office Space' , 'Comedy' , 'Mike Judge' ),
array('Matrix' , 'Action' , 'Andy / Larry Wachowski' ),
array('Lost In Translation' , 'Comedy / Drama' , 'Sofia Coppola' ),
array('A Beautiful Mind' , 'Drama' , 'Ron Howard' ),
array('Napoleon Dynamite' , 'Comedy' , 'Jared Hess' )
);
echo "<table border=\\"1\\">";
echo "<tr><th>Movies</th><th>Genre</th><th>Director</th></tr>";
for ( $row = 0; $row < count($movies); $row++ )
{
echo "<tr><td>";
for ( $column = 0; $column < count($movies); $column++ )
{
echo $movies[$row][$column] ;
}
echo "<td></tr>";
}

Loop through json array and group by key values

After json_decode I have the following Array :::
$json = Array ( [name] => Array ( [0] => Peter [1] => David ) [dep] => Array ( [0] => accounts [1] => sales ) [date] => Array ( [0] => 10/27/2015 [1] => 09/25/2015 ) );
How can I group the values by key so I get the following in a PHP foreach loop ? :::
<ul>
<li>Peter, accounts, 10/27/2015</li>
<li>David, sales, 09/25/2015</li>
</ul>
I've tried a similar foreach loop ( see below ) without the desired results, I'm able to print all the key & value's but I'm not able to group values by key eg. [1] :::
foreach($json as $row){
foreach($row as $key=>$val){
echo $key . ': ' . $val . '<br>';
}
}
Any assistance would be appreciated :::
You could use the following code to sort the list:
<?php
$json = [
"name" => ["Peter","David"],
"dep" => ["accounts", "sales"],
"date" => ["10/27/2015","09/25/2015"]
];
$final = [];
foreach($json as $section)
{
foreach($section as $key=>$info)
{
if(!isset($final[$key])) $final[$key] = "";
$final[$key] .= $info . ", ";
}
}
echo "<ul>";
foreach($final as $row)
{
echo "<li>" . substr($row, 0, strlen($row) - 2) . "</li>"; // -2 to remove the extra ", "
}
echo "</ul>";
?>
Result:
<ul>
<li>Peter, accounts, 10/27/2015</li>
<li>David, sales, 09/25/2015</li>
</ul>
Perhaps try something like this:
$arrayCount = count($json['name']);
$output = '<ul>';
for($i = 0; $i < $arrayCount; $i++) {
$output .= '<li>';
$output .= $json['name'][$i] . ', ';
$output .= $json['dep'][$i] . ', ';
$output .= $json['date'][$i];
$output .= '</li>';
}
$output .= '</ul>';
echo $output;
You would also be better off using an array format like this:
$json =
Array(
Array(
'name' => 'Peter',
'dep' => 'accounts',
'date' => '10/27/2015'
),
Array(
'name' => 'David',
'dep' => 'accounts',
'date' => '09/25/2015'
)
);
This is because you can create a easier to understand foreach loop like this:
$output = '<ul>';
foreach($json as $row) {
$output .= '<li>';
$output .= $row['name'] . ', ';
$output .= $row['dep'] . ', ';
$output .= $row['date'];
$output .= '</li>';
}
$output .= '</ul>';
echo $output;

php create navigation menu from multidimensional array dynamically

I did research on this, and wasn't able to find an exact answer. Most of the questions/answers on here pertaining to this seem to be unfinished. If anyone knows of a finished solution similar to my question, please point me in that direction!
Here is my array:
Array
(
['home'] => Array
(
[0] => sub-home1
[1] => sub-home2
)
['about'] => Array
(
[0] => sub-about
['about2'] => Array
(
[0] => sub-sub-about
)
)
['staff'] => Array
(
[0] => sub-staff1
[1] => sub-staff2
)
['contact'] => contact
)
And here is what I would like to turn it into:
<ul>
<li><a href="">home<a/>
<ul>
<li>sub-home1</li>
<li>sub-home2</li>
</ul>
</li>
<li><a href="">about<a/>
<ul>
<li>sub-about</li>
<li>about2
<ul>
<li><a href="">sub-sub-about<a/></li>
</ul>
</li>
</ul>
</li>
<li><a href="">staff<a/>
<ul>
<li>sub-staff1</li>
<li>sub-staff2</li>
</ul>
</li>
<li><a href="">contact<a/></li>
</ul>
The array will be dynamically generated, but will have a limit of 3 levels ex: about->about2->sub-sub-about. I tried going off of this question: PHP/MySQL Navigation Menu but they didn't really seem to come to a conclusion? I am familiar with foreach's whiles and for loops but I just can't seem to wrap my head around this one.
EDIT: Enzino, your code works!
Here is my solution:
<?php
function MakeMenu($items, $level = 0) {
$ret = "";
$indent = str_repeat(" ", $level * 2);
$ret .= sprintf("%s<ul>\n", $indent);
$indent = str_repeat(" ", ++$level * 2);
foreach ($items as $item => $subitems) {
if (!is_numeric($item)) {
$ret .= sprintf("%s<li><a href=''>%s</a>", $indent, $item);
}
if (is_array($subitems)) {
$ret .= "\n";
$ret .= MakeMenu($subitems, $level + 1);
$ret .= $indent;
} else if (strcmp($item, $subitems)){
$ret .= sprintf("%s<li><a href=''>%s</a>", $indent, $subitems);
}
$ret .= sprintf("</li>\n", $indent);
}
$indent = str_repeat(" ", --$level * 2);
$ret .= sprintf("%s</ul>\n", $indent);
return($ret);
}
$menu = Array(
'home' => Array("sub-home1", "sub-home2"),
'about' => Array("sub-about", "about2" => Array("sub-sub-about")),
'staff' => Array("sub-staff1", "sub-staff2"),
'contact' => "contact"
);
print_r($menu);
echo MakeMenu($menu);
?>
Calvin's solution worked for me. Here's the edited version. We can use more nested loops to get sub - sub menu items.
echo '<ul>';
foreach ($menu as $parent) {
echo '<li>' . $parent . '';
if (is_array($parent)) {
echo '<ul>';
foreach ($parent as $children) {
echo '<li>' . $children . '';
}
echo '</ul>';
}
echo '</li&gt';
}
echo '</ul>';
I think you can use recursion? Here is some pseudocode, not very familiar with php.
function toNavMenu(array A){
for each element in A{
echo "<li>" + element.name + ""
if (element is an array){
echo "<ul>"
toNavMenu(element)
echo "</ul>"
}
echo "</li>"
}
}
I would probably slightly adapt the array to be something like the following:
Array(
0 => Array(
'title' => 'Home',
'children' => Array()
),
1 => Array(
'title' => 'Parent',
'children' => Array(
0 => Array(
'title' => 'Sub 1',
'children' => Array(),
),
1 => Array(
'title' => 'Sub 2',
'children' => Array(
0 => Array(
'title' => 'Sub sub 2-1',
'children' => Array(),
),
),
),
)
)
)
With a structure like this you could use recursion to build your menu HTML:
function buildMenu($menuArray)
{
foreach ($menuArray as $node)
{
echo "<li><a href='#'/>" . $node['title'] . "</a>";
if ( ! empty($node['children'])) {
echo "<ul>";
buildMenu($node['children']);
echo "</ul>";
}
echo "</li>";
}
}

Creating php arrays from sql queries

I'm trying to create an array of arrays so I can build a dynamic menu, but I'm getting lost amongst the code. My output looks like this:
$menu = Array (
[0] => Array (
[text] => Home
[class] => 875
[link] => //Home
[show_condition] => TRUE
[parent] => 0
)
[1] => Array (
[text] => About
[class] => 326
[link] => //About
[show_condition] => TRUE
[parent] => 0
)
etc
etc
etc
[339] => Array (
[text] => Planner
[class] => 921
[link] => //Planner
[show_condition] => TRUE
[parent] => 45
)
)
And the two functions which should build the menu are:
function build_menu ( $menu ) {
$out = '<div class="container4">' . "\n";
$out .= ' <div class="menu4">' . "\n";
$out .= "\n".'<ul>' . "\n";
for ( $i = 1; $i <= count ( $menu )-1; $i++ )
{
if ( is_array ( $menu [ $i ] ) ) {//must be by construction but let's keep the errors home
if ( $menu [ $i ] [ 'show_condition' ] && $menu [ $i ] [ 'parent' ] == 0 ) {//are we allowed to see this menu?
$out .= '<li class="' . $menu [ $i ] [ 'class' ] . '"><a href="' . $menu [ $i ] [ 'link' ] . '">';
$out .= $menu [ $i ] [ 'text' ];
$out .= '</a>';
$out .= get_childs ( $menu, $i );
$out .= '</li>' . "\n";
}
}
else {
die ( sprintf ( 'menu nr %s must be an array', $i ) );
}
}
$out .= '</ul>'."\n";
$out .= "\n\t" . '</div>';
return $out . "\n\t" . '</div>';
}
function get_childs ( $menu, $el_id ) {
$has_subcats = FALSE;
$out = '';
$out .= "\n".' <ul>' . "\n";
for ( $i = 1; $i <= count ( $menu )-1; $i++ )
{
if ( $menu [ $i ] [ 'show_condition' ] && $menu [ $i ] [ 'parent' ] == $el_id ) {//are we allowed to see this menu?
$has_subcats = TRUE;
$add_class = ( get_childs ( $menu, $i ) != FALSE ) ? ' subsubl' : '';
$out .= ' <li class="' . $menu [ $i ] [ 'class' ] . $add_class . '"><a href="' . $menu [ $i ] [ 'link' ] . '">';
$out .= $menu [ $i ] [ 'text' ];
$out .= '</a>';
$out .= get_childs ( $menu, $i );
$out .= '</li>' . "\n";
}
}
$out .= ' </ul>'."\n";
return ( $has_subcats ) ? $out : FALSE;
}
But the menu is refusing to show any submenu levels - it only displays top level. Any ideas?
Thanks!
Your code is almost there - you may want to change mysql_fetch_array to mysql_fetch_assoc, and you can convert values as returned into the appropriate types using functions like intval:
$menu = array();
$sql = "SELECT TabName as text, TabID as class, TabPath as link, IsVisible as show_condition, ParentId as parent FROM dnn_SMA_Tabs WHERE PortalID = 3 AND IsVisible = 'True' ORDER BY TabOrder ASC";
$result = mysql_query($sql);
$index = 1;
while($row = mysql_fetch_assoc($result)) {
$row['parent'] = intval($row['parent']);
$menu[$index] = $row;
$index++;
}
You'll need to convert show_condition to the appropriate type - how to do that probably depends on what column type IsVisible is.
i see your array has indexes from [0] to [399]
Array (
[0] => Array (
[text] => Home
[class] => 875
[link] => //Home
[show_condition] => TRUE
[parent] => 0
)
[1] => Array (
[text] => About
[class] => 326
[link] => //About
[show_condition] => TRUE
[parent] => 0
)
etc
etc
etc
[339] => Array (
[text] => Planner
[class] => 921
[link] => //Planner
[show_condition] => TRUE
[parent] => 45
) )
but you try to show items from [1] to [340]
for ( $i = 1; $i <= count ( $menu ); $i++ )
count($menu) returns 340 ([0]->[399])
Solution: for ( $i = 0; $i < count ( $menu ); $i++ )
start from 0 and go until 399 (strictly < 340)
I would do it in an other way: object oriented.
class Menu {
private $children = array();
private $name = '';
private $link = '';
private $class = '';
private $show = TRUE;
function __construct($name, $class, $link, $show = TRUE, $parent = null) {
$this->name = $name;
$this->link = $link;
$this->class = $class;
$this->show = $show;
if(!is_null($parent)) {
$parent->addChild($this);
}
}
function addChild(Menu $child) {
$this->children[] = $child;
}
// ... remaining getters (and probably setters)
}
Then you can build the menu like this:
$home = new Menu('Home', '875', '//Home');
$about = new Menu('About', '326', '//About');
//...
$planner = new Menu('Planner', '921', '//Planner', true, $home);
$menu = array($home, $about,...);
This is just one example. I am aware that this would mean you create 340 variables to hold your menu. With other setter and getter methods you can do it better, this is just a fast 'sketch'.
You can build the menu like this:
function build_menu ( $menu, $showContainer = false) {
$out = '';
if($showContainer) {
$out = '<div class="container4">' . "\n";
$out .= ' <div class="menu4">' . "\n";
}
if(!empty($menu)) {
$out .= '<ul>' . "\n";
for ($entry in $menu) {
if($entry->getShow()) {//are we allowed to see this menu?
$out .= '<li class="' . $entry->getClass() . '"><a href="' . $entry->getLink() . '">';
$out .= $entry->getText();
$out .= '</a>';
$out .= "\n" . build_menu($entry->getChildren());
$out .= '</li>' . "\n";
}
}
$out .= '</ul>'."\n";
}
if($showContainer) {
$out .= "\n\t" . '</div>';
$out .= "\n\t" . '</div>';
}
return $out;
}
I didn't test the code, but this is the idea behind it. If you have no experience with OOP and php have a look at the official documentation.
And also note that this requires PHP5.

Categories