I want to merge array which have same key to be one. Example
$options = array(
array("group" => "header","title" => "Content 1"),
array("group" => "header","title" => "Content 2"),
array("group" => "menu","title" => "Content 3"),
array("group" => "content","title" => "Content 4"),
array("group" => "content","title" => "Content 5"),
array("group" => "content","title" => "Content 6"),
array("group" => "footer","title" => "Content 7")
);
foreach ($options as $value) {
if ($value['group']) {
echo "<div class='{$value['group']}'>";
echo $value['title'];
echo "</div>";
}
}
Current output is
<div class='header'>Content 1</div><div class='header'>Content 2</div><div class='menu'>Content 3</div><div class='content'>Content 4</div><div class='content'>Content 5</div><div class='content'>Content 6</div><div class='footer'>Content 7</div>
What I want here is to be
<div class='header'>
Content 1
Content 2
</div>
<div class='menu'>
Content 3
</div>
<div class='content'>
Content 4
Content 5
Content 6
</div>
<div class='footer'>
Content 7
</div>
Let me know
$grouped = array();
foreach($options as $option) {
list($group, $title) = array_values($option);
if (!isset($grouped[$group])) {
$grouped[$group] = array();
}
$grouped[$group][] = $title;
}
foreach ($grouped as $group => $titles) {
echo sprintf('<div class="%s">%s</div>', $group, implode('', $titles));
}
$groups = array ();
foreach ( $options as $value ) {
if ( !isset ( $groups[$value['group']] ) ) {
$groups[]['group'] = $value['group']
}
$groups[$value['group']]['title'][] = $value['title'];
}
foreach ( $groups as $group ) {
echo "<div class="{$group['group']}">";
echo implode ( "\n", $group['title'] );
echo "</div>";
}
This should work, but if it doesn't matter to you, you could also just change the structure of your hardcoded-array, then you wouldn't need my first foreach.
Related
I want to loop through the unknown depth array with RecursiveIteratorIterator in SELF::FIRST mode along with RecursiveArrayIterator.
If the array value is an array, I will open a DIV so the "subarray" will be inside this DIV. Something like
$array = array(
'key0' => '0',
'key1' => array(
'value0' => '1',
'value1' => '2',
),
'key2' => '3',
'key3' => array(
'value2' => '4',
'value3' => array(
'value4' => '5'
),
'value4' => array(
'value5' => '6'
),
),
);
Then the HTML should be:
<div>
<div>
<p>key0 is 0</p>
</div>
<div>
<p>key1</p>
<div>
<p>value0 is 1</p>
<p>value1 is 2</p>
</div>
</div>
<div>
<p>key2 is 3</p>
</div>
<div>
<p>key3</p>
<div>
<p>value2 is 4</p>
<p>value3</p>
<div>
<p>value4 is 5</p>
</div>
<p>value4</p>
<div>
<p>value5 is 6</p>
</div>
</div>
</div>
</div>
But the problem is my code can only close 1 <div> tag each time. I have no idea how to remember how deep was there. So I can close to a for loop and echo </div>.
My current code:
<?php
echo '<div>';
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($iterator_array), RecursiveIteratorIterator::SELF_FIRST);
$is_start = true;
$last_element = '';
foreach($iterator as $key => $value) {
if(is_array($value) && $is_start) {
echo '<div><p>' . $key . '</p>';
$is_start = false;
$last_element = end($value);
} elseif(is_array($value) && !$is_start) {
echo '</div><div><p>' . $key . '</p>';
$last_element = end($value);
} elseif(!is_array($value)) {
echo '<div><p>' . $key . ' is ' . $value . '</p></div>';
if($last_element == $value) {
echo '</div>';
}
}
}
echo '</div>';
?>
Use this recursive function
May be it will help you
get_div($array);
function get_div($arr) {
foreach($arr as $k => $a){
echo '<div>';
if(is_array($a)) {
echo "<p>".$k."</p>";
get_div($a);
} else {
echo "<p>".$k." is ".$a."</p>";
}
echo '</div>';
}
}
I have a JSON file that contain this:
"Menus": [{
"MenuId": "1",
"MenuName": "Perencanaan dan Pengadaan",
"MenuParent": "",
"MenuLink": ""
}, {
"MenuId": "1-1",
"MenuName": "RKA / DPA",
"MenuParent": "1",
"MenuLink": ""
}, {
"MenuId": "1-1-1",
"MenuName": "Daftar RKA / DPA",
"MenuParent": "1-1",
"MenuLink": "rkbu"
},
I want to put that data into unordered list dynamically. So the output I want is like this (with 3 level list):
Perencanaan dan Pengadaan
RKA / DPA
Daftar RKA / DPA
I have tried this code:
echo "<ul>";
foreach($get_data['Menus'] as $node){
if(strlen($node['MenuId']) == 1){
echo "<li>" . $node['MenuName'];
echo "</li>";
}
echo "<ul>";
if(strlen($node['MenuId']) == 3){
echo "<li>".$node['MenuName']."</li>";
}
if(strlen($node['MenuId']) == 5){
echo "<ul>";
echo "<li>".$node['MenuName']."</li>";
echo "</ul>";
}
echo "</ul>";
}
echo "</ul>";
But I find that it is not dynamic because it depends on string length. I've read that the best method is using recursive method. But I cannot find the recursive pattern of my JSON file. Can anybody help me find the solution? Thanks
I don't think it is possible to make recursive calls directly on your flat JSON data.
I suggest you first convert your flat data to a multidimensional array and afterwards recursively generate your menu.
I took parts of the code from here: Dynamically creating/inserting into an associative array in PHP
$get_data = array(
array(
"MenuId" => "1",
"MenuName" => "Perencanaan dan Pengadaan",
"MenuParent" => "",
"MenuLink" => ""
),
array(
"MenuId" => "1-1",
"MenuName" => "RKA / DPA",
"MenuParent" => "1",
"MenuLink" => ""
),
array(
"MenuId" => "1-1-1",
"MenuName" => "Daftar RKA / DPA",
"MenuParent" => "1-1",
"MenuLink" => "rkbu"
)
);
function insert_into(&$array, array $keys, $value) {
$last = array_pop($keys);
foreach($keys as $key) {
if(!array_key_exists($key, $array) ||
array_key_exists($key, $array) && !is_array($array[$key])) {
$array[$key]['items'] = array();
}
$array = &$array[$key]['items'];
}
$array[$last]['value'] = $value;
}
function create_menu($menuItems) {
$content = '<ul>';
foreach($menuItems as $item) {
$content .= '<li>' . $item['value'];
if(isset($item['items']) && count($item['items'])) {
$content .= create_menu($item['items']);
}
$content .= '</li>';
}
$content .= '</ul>';
return $content;
}
$menuItems = array();
foreach($get_data as $item) {
$levels = explode('-', $item['MenuId']);
insert_into($menuItems, $levels, $item['MenuName']);
}
print_r($menuItems);
print create_menu($menuItems);
DEMO: http://3v4l.org/dRK4f
Output:
Array (
[1] => Array (
[value] => Perencanaan dan Pengadaan
[items] => Array (
[1] => Array (
[value] => RKA / DPA
[items] => Array (
[1] => Array (
[value] => Daftar RKA / DPA
)
)
)
)
)
)
<ul>
<li>Perencanaan dan Pengadaan
<ul>
<li>RKA / DPA
<ul>
<li>Daftar RKA / DPA</li>
</ul>
</li>
</ul>
</li>
</ul>
First Array Output:
print_r($categories);
Array
(
[1] => Accounting & Financial
[2] => Advertising Services
[3] => Awards & Incentives
[4] => Business Consultants
[5] => Career Services
[6] => Creative Services
[7] => Data Management
[8] => Distributors & Agents
)
Second array Output:
print_r($Service_Provider_Id['Category']);
Array
(
[0] => Array
(
[id] => 1
[category] => Accounting & Financial
)
[1] => Array
(
[id] => 2
[category] => Advertising Services
)
)
My Below code showing all checkbox base on first array
<?phpforeach ($categories as $key => $value) { ?>
<div class="checkboxes-div">
<input type="checkbox" id="CategoryCategory<?php echo $key; ?>" value="<?php echo $key?>" name="data[Category][Category][]">
<label class="selected" for="CategoryCategory<?php echo $key; ?>">
<?php echo $value; ?>
</label>
</div>
<?php } ?>
if second array category's key value match with first array value so i want to selected checkbox
since in_array() will not work in multidimensional array you have to use two foreach loop. so try this
<?php
$categories=Array
(
"1" => "Accounting & Financial",
"2" => "Advertising Services",
"3" => "Awards & Incentives",
"4" => "Business Consultants",
"5" => "Career Services",
"6" => "Creative Services",
"7" => "Data Management",
"8" => "Distributors & Agents"
) ;
$Service_Provider_Id['Category'] = Array
(
"0" => Array
(
"id" => "1" ,
"category" => "Accounting & Financial"
),
"1" => Array
(
"id" => "2",
"category" => "Advertising Services"
)
);
?>
<?php foreach ($categories as $key => $value) { ?>
<div class="checkboxes-div">
<input type="checkbox" id="CategoryCategory<?php echo $key; ?>" value="<?php echo $key?>" name="data[Category][Category][]"
<?php foreach ($Service_Provider_Id['Category'] as $keys => $values) { foreach ($values as $keys2 => $values2) { if(in_array($value,$Service_Provider_Id['Category'][$keys])) { ?> checked <?php } } } ?> >
<label class="selected" for="CategoryCategory<?php echo $value; ?>">
<?php echo $value; ?>
</label>
</div>
<?php } ?>
thing is you want to search an element in a multi dimensional array, so you must use a function for this. Try the code below
function ArraySearchRecursive($Needle, $Haystack, $NeedleKey = "", $Strict = false, $Path = array()) {
if (!is_array($Haystack))
return false;
foreach ($Haystack as $Key => $Val) {
if (is_array($Val) &&
$SubPath = ArraySearchRecursive($Needle, $Val, $NeedleKey, $Strict, $Path)) {
$Path = array_merge($Path, Array($Key), $SubPath);
return $Path;
} elseif ((!$Strict && $Val == $Needle &&
$Key == (strlen($NeedleKey) > 0 ? $NeedleKey : $Key)) ||
($Strict && $Val === $Needle &&
$Key == (strlen($NeedleKey) > 0 ? $NeedleKey : $Key))) {
$Path[] = $Key;
return $Path;
}
}
return false;
}
and then
<?php foreach ($categories as $key => $value) { ?>
<div class="checkboxes-div">
<input type="checkbox" id="CategoryCategory<?php echo $key; ?>" value="<?php echo $key; ?>" <?php if (ArraySearchRecursive($value, $Service_Provider_Id['Category'])) { ?> checked <?php } ?> name="data[Category][Category][]">
<label class="selected" for="CategoryCategory<?php echo $key; ?>">
<?php echo $value; ?>
</label>
</div>
<?php } ?>
This works. I personally tried it.
So right now i have an array named $socialMeta, containing:
Array (
[0] => Array (
[socialFacebook] => Array (
[0] => http://www.facebook.com/someUsername
)
)
[1] => Array (
[socialYoutube] => Array (
[0] => http://www.youtube.com/user/someUsername
)
)
[2] => Array (
[socialSoundcloud] => Array (
[0] => http://www.soundcloud.com/someUsername
)
)
)
From this array I need to create the following output:
<div class="social">
Add us on <span>Facebook</span>
Visit us on <span>Youtube</span>
Visit us on <span>Souncloud</span>
</div>
Please not that there are different anchor text for the first link.
For anchor classes i can use $socialMeta key to make whole process a bit easier.
<?php if (!empty($socialMeta)) { ?>
<div class="social">
<?php foreach ($socialMeta as $rows) {?>
<?php foreach ($rows as $key => $val) {?>
<?php
switch ($key) {
case "socialFacebook":
$title = "Facebook";
$class = "fb";
break;
case "socialYoutube":
$title = "Youtube";
$class = "yt";
break;
case "socialSoundcloud":
$title = "Souncloud";
$class = "sc";
break;
}
?>
Add us on <span><?php echo $title; ?></span>
<?php }?>
<?php }?>
</div>
<?php }?>
Start by identifying the network for each element in the array (I assume the name is $array in the following examples):
function add_network($array) {
static $networks = array('Facebook', 'Youtube', 'Soundcloud');
foreach($networks as $network)
if (isset($array['social' . $network])) {
$array['network'] = $network;
return $array;
}
//None found
$array['network'] = false;
return $array;
}
$array = array_map('add_network', $array);
Then transform the array (you should find a better name for this function):
function transform_array($a) {
static $classes = array('Youtube' => 'yt', 'Facebook' => 'fb', 'Soundcloud' => 'sc');
$network = $a['network'];
$class = $classes[$network];
$url = $a['social' . $network][0]
return array('network' => $network,
'url' => $url,
'class' => $class);
}
$array = array_map('transform_array', $array);
And now just loop over the elements of $array:
foreach($array as $row) {
$network = $row['network'];
$url = $row['url'];
$class = $row['class'];
if ($network === 'Facebook')
$link_text = 'Add us on <span>%s</span>';
else
$link_text = 'Visit us on <span>%s</span>'
$link_text = sprintf($link_text, $network);
printf('%s',
$url, $class, $link_text);
}
<?php
function flattenArray(array $input){
$nu = array();
foreach($input as $k => $v){
if(is_array($v) && count($v) == 1){
$nu[key($v)] = current($v);
if(is_array($nu[key($v)]) && count($v) == 1)
$nu[key($v)] = current($nu[key($v)]);
}
else
$nu[$k] = $v;
}
return $nu;
}
// here you can maintain the sortorder of the output and add more social networks with the corresponding URL-text...
$urlData = array(
'socialFacebook' => 'Add us on <span>Facebook></span>',
'socialYoutube' => 'Visit us on <span>Youtube</span>',
'socialSoundcloud' => 'Visit us on <span>Souncloud</span>',
);
$testArray = array(
array('socialFacebook' => array('http.asdfsadf')),
array('socialYoutube' => array('http.asdfsadf')),
array('socialSoundcloud' => array('http.asdfsadf'))
);
$output = flattenArray($testArray);
HERE WE GO
echo '<div class="social">';
foreach($urlData as $network => $linkText){
if(!empty($output[$network]))
echo sprintf('%s</span>', $output[$network], $linkText);
}
echo '</div>';
I have a simplepie feed that spits out multiple feeds from each of the URL's that are loaded into a a associative array.
This associative array is used to sort the arrays alphabetically using the values.
I'm trying to use that same value sort and keep all of the arrays with the same URL or value together so that when the foreach loop runs I get one div per URL containning all the feeds from that URL for the day
<?php
require_once('php/autoloader.php');
$feed = new SimplePie(); // Create a new instance of SimplePie
// Load the feeds
$urls = array(
'http://abcfamily.go.com/service/feed?id=774372' => 'abc',
'http://animal.discovery.com/news/news.rss' => 'animalplanet',
'http://www.insideaolvideo.com/rss.xml' => 'aolvideo',
'http://feeds.bbci.co.uk/news/world/rss.xml' => 'bbcwn',
'http://www.bing.com' => 'bing',
'http://www.bravotv.com' => 'bravo',
'http://www.cartoonnetwork.com' => 'cartoonnetwork',
'http://feeds.cbsnews.com/CBSNewsMain?format=xml' => 'cbsnews',
'http://www.clicker.com/' => 'clicker',
'http://feeds.feedburner.com/cnet/NnTv?tag=contentBody.1' => 'cnet',
'http://www.comedycentral.com/' => 'comedycentral',
'http://www.crackle.com/' => 'crackle',
'http://www.cwtv.com/feed/episodes/xml' => 'cw',
'http://disney.go.com/disneyxd/' => 'disneyxd',
'http://www.engadget.com/rss.xml' => 'engadget',
'http://syndication.eonline.com/syndication/feeds/rssfeeds/video/index.xml' => 'eonline',
'http://sports.espn.go.com/espn/rss/news' => 'espn',
'http://facebook.com' => 'facebook',
'http://flickr.com/espn/rss/news' => 'flickr',
'http://www.fxnetworks.com//home/tonight_rss.php' => 'fxnetworks',
'http://www.hgtv.com/' => 'hgtv',
'http://www.history.com/this-day-in-history/rss' => 'history',
'http://rss.hulu.com/HuluRecentlyAddedVideos?format=xml' => 'hulu',
'http://rss.imdb.com/daily/born/' => 'imdb',
'http://www.metacafe.com/' => 'metacafe',
'http://feeds.feedburner.com/Monkeyseecom-NewestVideos?format=xml' => 'monkeysee',
'http://pheedo.msnbc.msn.com/id/18424824/device/rss/' => 'msnbc',
'http://www.nationalgeographic.com/' => 'nationalgeographic',
'http://dvd.netflix.com/NewReleasesRSS' => 'netflix',
'http://feeds.nytimes.com/nyt/rss/HomePage' => 'newyorktimes',
'http://www.nick.com/' => 'nickelodeon',
'http://www.nickjr.com/' => 'nickjr',
'http://www.pandora.com/' => 'pandora',
'http://www.pbskids.com/' => 'pbskids',
'http://www.photobucket.com/' => 'photobucket',
'http://feeds.reuters.com/Reuters/worldNews' => 'reuters',
'http://www.revision3.com/' => 'revision3',
'http://www.tbs.com/' => 'tbs',
'http://www.theverge.com/rss/index.xml' => 'theverge',
'http://www.tntdrama.com/' => 'tnt',
'http://www.tvland.com/' => 'tvland',
'http://www.vimeo.com/' => 'vimeo',
'http://www.vudu.com/' => 'vudu',
'http://feeds.wired.com/wired/index?format=xml' => 'wired',
'http://www.xfinitytv.com/' => 'xfinitytv',
'http://www.youtube.com/topic/4qRk91tndwg/most-popular#feed' => 'youtube',
);
$feed->set_feed_url(array_keys($urls));
$feed->enable_cache(true);
$feed->set_cache_location('cache');
$feed->set_cache_duration(1800); // Set the cache time
$feed->set_item_limit(0);
$success = $feed->init(); // Initialize SimplePie
$feed->handle_content_type(); // Take care of the character encoding
?>
<?php require_once("inc/connection.php"); ?>
<?php require_once("inc/functions.php"); ?>
<?php include("inc/header.php"); ?>
<?php
// Sort it
$feed_items = array();
$items = $feed->get_items();
$urls = array_unique($urls);
foreach ($urls as $url => $image) {
$unset = array();
$feed_items[$url] = array();
foreach ($items as $i => $item) {
if ($item->get_feed()->feed_url == $url) {
$feed_items[$url][] = $item;
$unset[] = $i;
}
}
foreach ($unset as $i) {
unset($items[$i]);
}
}
foreach ($feed_items as $feed_url => $items) {
if (empty($items)) {
?>
<div class="item"><img src="images/boreds/<?php echo $urls[$feed_url] ?>.png"/><p>Visit <?php echo $urls[$feed_url] ?> now!</p></div>
<?
continue;
}
$first_item = $items[0];
$feed = $first_item->get_feed();
?>
<?php
$feedCount = 0;
foreach ($items as $item ) {
$feedCount++;
?>
<div class="item"><strong id="amount"><?php echo $feedCount; ?></strong><img src="images/boreds/<?php echo $urls[$feed_url] ?>.png"/><p><?php echo $item->get_title(); ?></p></div>
<?php
}
}
?>
<?php require("inc/footer.php"); ?>
Maybe you can use this one:
$feed = new SimplePie();
$feed->set_feed_url('http://myfirstfeed','http://mysecondfeed');
foreach( $feed->get_items() as $k => $item ) {
echo "<div id='".$k.'">";
echo $item->get_permalink();
echo $title = $item->get_title();
echo $item->get_date('j M Y, g:i a');
echo $item->get_content();
echo "</div>";
}