is it possible to use foreach in foreach in codeigniter - php

Here is my function - I get an error.
In variable $data['stars'] I got maximum numbers of stars with is invalid
I want correct stars from database because actually stars table are different so that's why.
Is it possible to get stars from another table in this foreach to get accurate value?
public function dbmovies()
{
$this->db->order_by("videos_id", "desc");
$this->db->where(array('publication' => 1, 'is_tvseries' => 0));
$query = $this->db->get('videos');
//get stars
foreach ($query->result() as $key => $value) {
$this->db->where_in('star_id', $value->stars);
$queryStars = $this->db->get('star');
$stars=array();
foreach ($queryStars->result() as $star) {
$stars[] = $star->star_name;
$starone = implode(", ", $stars);
}
$data['videoId'] = $value->videos_id;
$data['imdbid'] = $value->imdbid;
$data['title'] = $value->title;
$data['description'] = $value->description;
$data['duration'] = $value->runtime;
$data['views'] = $value->total_view;
$data['stars'] = $starone;
$alldata[] = $data;
}
$get['data'] = $alldata;
echo json_encode($get, JSON_PRETTY_PRINT);
}
And tge output I get like this
{
"data": [
{
"videoId": "47",
"imdbid": "tt2935510",
"title": "Ad Astra",
"description": "<p>The near future, a time when both hope and hardships drive humanity to look to the stars and beyond. While a mysterious phenomenon menaces to destroy life on planet Earth, astronaut Roy McBride undertakes a mission across the immensity of space and its many perils to uncover the truth about a lost expedition that decades before boldly faced emptiness and silence in search of the unknown.<\/p>",
"duration": "123 Min",
"views": "2",
"stars": "Brad Pitt"
},
{
"videoId": "45",
"imdbid": "tt8243160",
"title": "Hacker",
"description": "<p>13-year-old Benjamin discovers that his mother didn\u2019t die in an accident as he was led to believe. The trail leads to high-ranking officials in the Danish Secret Service. \"Trust no one!\", he is told.<\/p>",
"duration": "96 Min",
"views": "93",
"stars": "Brad Pitt, Rumle Krs"
},
{
"videoId": "44",
"imdbid": "tt7131622",
"title": "Once Upon a Time... in Hollywood",
"description": "<p>A faded television actor and his stunt double strive to achieve fame and success in the film industry during the final years of Hollywood's Golden Age in 1969 Los Angeles.<\/p>",
"duration": "161 Min",
"views": "71",
"stars": "Brad Pitt, Rumle Krs, Leonardo DiCaprio"
},
Can anyone please help me?

You have to move the $starone variable to the outside of the foreach loop so that it doesn't get overwritten inside the loop :
foreach ($queryStars->result() as $star) {
$stars[] = $star->star_name;
}
$starone = implode(", ", $stars);

Add empty array before foreach $stars=array();
$stars=array();
foreach ($queryStars->result() as $star) {
$stars[] = $star->star_name;
$starone = implode(", ", $stars);
}

Related

How to randomize json

I have a randquotes.json file
{
"author": "William Shakespeare",
"quotes": "A brave flea is a flea that can dare to get its breakfast on the lips of a lion."
},
{
"author": "Winston Churchill",
"quotes": "We live with what we get, but we bring life to what we give."
},
{
"author": "Wolfgang von Gothe",
"quotes": "Knowledge is not enough, we must practice it. Intention is not enough, we must do it."
}
Then I want "author" and "quotes" to be generated randomly with php
How?
thanks for help
Assuming you actually have valid a JSON string...
Convert the json to a PHP datatype using json_decode()
find out how large the array is
generate a random number between 0 and array size
Return that array occurance, I did that as a json string again using json_encode()
$json_string = '
[
{
"author": "William Shakespeare",
"quotes": "A brave flea is a flea that can dare to get its breakfast on the lips of a lion."
},
{
"author": "Winston Churchill",
"quotes": "We live with what we get, but we bring life to what we give."
},
{
"author": "Wolfgang von Gothe",
"quotes": "Knowledge is not enough, we must practice it. Intention is not enough, we must do it."
}
]';
$arr = json_decode($json_string);
// How big is the array
$max = count($arr) -1;
$rand_idx = rand(0, $max);
echo json_encode($arr[$rand_idx]);

PHP display product by category

What i want is to display all products that below to category with id 1 in.
Is displaying all products but as well looping 3 times category with each products what i want is to be .
one category with holder each and all product in each
here is my code:
$query_cat = query("SELECT * FROM categories");
$query = query("SELECT * FROM products WHERE product_category_id = '1'");
confirm($query_cat, $query);
$cat = fetch_array($query_cat);
while(($row = fetch_array($query))){
$category[] = array(
'category_id'=>$cat['cat_id'],
'category_title'=>$cat['cat_title'],
'each' => $item[] = array (
'product_id'=>$row['product_id'],
'name'=>$row['product_title'],
'product_tags'=>$row['product_category'],
'partner_name_title'=>$row['partner_name_title'],
'product_category_id'=>$row['product_category_id'],
'image'=> $produc_img,
'price'=>$row['product_price'],
'discount'=>$row['product_discount'],
'from_date'=>$row['start_discount'],
'to_date'=>$row['finish_discount'],
'sold'=>$row['counter_sold'],
'desc'=>$row['product_about'],
'location_address'=>$row['product_address'],
'location'=>$row['product_location'],
'partner_phone'=>$row['product_phone'],
'partner_email'=>$row['product_email'],
'partner_open_time'=>$row['product_open_time'],
'partner_website'=>$row['product_website'],
'instagram_page'=>$row['instagram_page'],
'facebook_page'=>$row['facebook_page'],
'product_prev'=>$row['product_prev'],
'exp'=>$row['expire']
)
);
}
}
header("Content-Type: application/json");
echo json_encode(array('pro'=>$category), JSON_PRETTY_PRINT);
OUTPUT:
{
"pro": [
{
"category_id": "1",
"category_title": "Food & Drink",
"each": {
"product_id": "84",
"name": "Night Diner",
"product_tags": "appetisers, food , health food, amazing , good .",
"partner_name_title": "Apantisi",
"product_category_id": "1",
"image": null,
"price": "1",
"discount": "-30%",
"from_date": "2020-07-25",
"to_date": "2020-12-25",
"sold": "0",
"desc": "Our restaurant proposing you to spend amazing time with you family get the taste of Caribbeans dishes \r\nOur restaurant proposing you to spend amazing time with you family get the taste of Caribbeans dishes \r\nOur restaurant proposing you to spend amazing time with you family get the taste of Caribbeans dishes ",
"location_address": "Glyfu 5 a",
"location": "Nicosia",
"partner_phone": "+357 97 832 983",
"partner_email": "apantisi#gmail.com",
"partner_open_time": "12:00-22:00",
"partner_website": "www.apantisi.com.cy",
"instagram_page": "instagram.com\/apantisi",
"facebook_page": "facebook.com\/apantisi",
"product_prev": "This coupon gives you discount -30% on any reserved table in our restaurant .",
"exp": "no"
}
},
{
"category_id": "1",
"category_title": "Food & Drink",
"each": {
"product_id": "85",
"name": "Princess Hair ",
"product_tags": "hair , extensions hair, beauty , saloon ",
"partner_name_title": "Princess Hair",
"product_category_id": "1",
"image": null,
"price": "1",
"discount": "-50%",
"from_date": "2020-07-25",
"to_date": "2020-12-25",
"sold": "2",
"desc": "is the wonderful saloon hair for you we offer you best quality of hair \r\nis the wonderful saloon hair for you we offer you best quality of hair \r\nis the wonderful saloon hair for you we offer you best quality of hair \r\nis the wonderful saloon hair for you we offer you best quality of hair ",
"location_address": " 1 Michail Georgalla Street",
"location": "Nicosia",
"partner_phone": "+357 97 832 983",
"partner_email": "hair#gmail.com",
"partner_open_time": "8:00-15:00 ",
"partner_website": "www.hair.com.cy",
"instagram_page": "instagram.com\/.hair",
"facebook_page": "instagram.com\/.hair",
"product_prev": "We offer you discount with -50% on our product bt code from coalaboom \/ use the chance to come with the code by issue date ",
"exp": "no"
}
}
but what i need is :
"pro": [
{
"category_id": "1",
"category_title": "Food & Drink",
"each": {
"product_id": "84",
"name": "Night Diner",
"product_tags": "appetisers, food , health food, amazing , good .",
"partner_name_title": "Apantisi",
"product_category_id": "1",
"image": null,
"price": "1",
"discount": "-30%",
"from_date": "2020-07-25",
"to_date": "2020-12-25",
"sold": "0",
"desc": "Our restaurant proposing you to spend amazing time with you family get the taste of Caribbeans dishes \r\nOur restaurant proposing you to spend amazing time with you family get the taste of Caribbeans dishes \r\nOur restaurant proposing you to spend amazing time with you family get the taste of Caribbeans dishes ",
"location_address": "Glyfu 5 a",
"location": "Nicosia",
"partner_phone": "+357 97 832 983",
"partner_email": "apantisi#gmail.com",
"partner_open_time": "12:00-22:00",
"partner_website": "www.apantisi.com.cy",
"instagram_page": "instagram.com\/apantisi",
"facebook_page": "facebook.com\/apantisi",
"product_prev": "This coupon gives you discount -30% on any reserved table in our restaurant .",
"exp": "no"
},
{
"product_id": "85",
"name": "Princess Hair ",
"product_tags": "hair , extensions hair, beauty , saloon ",
"partner_name_title": "Princess Hair",
"product_category_id": "1",
"image": null,
"price": "1",
"discount": "-50%",
"from_date": "2020-07-25",
"to_date": "2020-12-25",
"sold": "2",
"desc": "is the wonderful saloon hair for you we offer you best quality of hair \r\nis the wonderful saloon hair for you we offer you best quality of hair \r\nis the wonderful saloon hair for you we offer you best quality of hair \r\nis the wonderful saloon hair for you we offer you best quality of hair ",
"location_address": " 1 Michail Georgalla Street",
"location": "Nicosia",
"partner_phone": "+357 97 832 983",
"partner_email": "hair#gmail.com",
"partner_open_time": "8:00-15:00 ",
"partner_website": "www.hair.com.cy",
"instagram_page": "instagram.com\/.hair",
"facebook_page": "instagram.com\/.hair",
"product_prev": "We offer you discount with -50% on our product bt code from coalaboom \/ use the chance to come with the code by issue date ",
"exp": "no"
}
}
I want display product in each by category 1
Replace your while with:
$category = [
'category_id'=>$cat['cat_id'],
'category_title'=>$cat['cat_title'],
'each' => [],
];
while(($row = fetch_array($query))){
$category['each'][] = [
'product_id'=>$row['product_id'],
// ... rest of $row attributes
];
}
With this there will be one category and each product will have its entry in each key.

JSON PHP foreach empty value

I'm working with PHP and JSON. I have this example of a JSON foreach loop, with this example I want to get lat/lon to add a marker in Google Maps:
"data": [
{
"end_time": "2016-02-09T22:30:00-0200",
"name": "6\u00ba Rebanh\u00e3o de Carnaval - Comunidade Cen\u00e1culo",
"place": {
"name": "Comunidade Cen\u00e1culo",
"location": {
"city": "Franca",
"country": "Brazil",
"latitude": "",
"longitude": "",
"state": "SP",
"street": "Dom Pedro I, 1040, Jardim Petr\u00e1glia"
},
"id": "410657548946610"
},
"start_time": "2016-02-05T19:30:00-0200",
"id": "940527599373114"
}
]
My problem is, some of results of latitude and longitude are empty. I want to put a specific value on it, but on each empty I want to add lat + 0.02.
For example, in first empty value I want to put this lat 40.700106, and the next empty value I want to put this 40.700106 + 0.02.
I just don't want 2 markers in same location.
How can I do this?
EDIT:
foreach($json3 ->data as $mydata1)
{
$latitude = $mydata1->place->location->latitude;
if(empty($latitude ))
{
$latitude = $latitude + 0.02;
echo ' lat :'.$latitude ;
}
}
this way i replace the empty value, but they dont add the + 0.02 on each value
You can save the previous latitude and use it.
Something like this:
$previousLatitude = null;
foreach($json3 ->data as $mydata1) {
$latitude = $mydata1->place->location->latitude;
if(empty($latitude ))
{
$latitude = $previousLatitude + 0.02;
echo ' lat :'.$latitude ;
}
$previousLatitude = $latitude
}

How can I query in laravel from a column in the db that has single values and arrays?

I am doing a complex query that looks at data in the database from a column that has single and multiple values depending on whats added. Here is a snippet of what might be sent out:
[
{
"id": 1,
"offer_title": "",
"offer headline": "",
"offer_subheader": "small subheader",
"image": "2015-08-10-09-2.png",
"thumbnail": "2015-08-10-09-1.png",
"offer_terms": "the terms",
"venue_name": "the venue number 2",
"venue_headline": "the headline",
"venue_description": "the venue is awesome",
"venue_phone_number": "00445676833",
"venue_website": "site.co.uk",
"venue_latitude": 999999.99,
"venue_longitude": -999999.99,
"offer_when": "tomorrow",
"days": "tuesday",
"featured_date": "",
"offer_end_time": "08:50",
"offer_start_time": "08:50",
"created_at": "2015-08-10 09:50:50",
"updated_at": "2015-08-11 07:50:59",
"deleted_at": null,
"offer_headline": "large header",
"venue_address": "55 road",
"offer_start_date": "08/11/2015",
"offer_end_date": "08/11/2015"
},
{
"id": 2,
"offer_title": "",
"offer headline": "",
"offer_subheader": "the subheader",
"image": "2015-08-11-09-logotype.png",
"thumbnail": "2015-08-11-09-logotype.png",
"offer_terms": "terms",
"venue_name": "a name",
"venue_headline": "this headline",
"venue_description": "the venue is cool",
"venue_phone_number": "00445676833",
"venue_website": "anothersite.co.uk",
"venue_latitude": 999999.99,
"venue_longitude": -999999.99,
"offer_when": "tomorrow",
"days": "monday,tuesday,wednesday",
"featured_date": "",
"offer_end_time": "20:29",
"offer_start_time": "15:29",
"created_at": "2015-08-11 09:31:12",
"updated_at": "2015-08-11 09:31:12",
"deleted_at": null,
"offer_headline": "the header",
"venue_address": "55 road",
"offer_start_date": "08/11/2015",
"offer_end_date": "08/11/2015"
}
]
As you can see in each object there is a column called days each one has either a list or a single value. What I am trying to achieve is by getting the current day today query the db and show up items in here that match the current day today so for example, its tuesday so all offers with either 'tuesday' or 'tuesday,wednesday,friday' should show up as it's tuesday today, if they don't they would show up another day. Here is what I have tried so far which only ever gives me the single valued days as the result not the one with the array in it:
public function getOffers(Offer $offer)
{
$mytime = Carbon::now();
$today = $mytime->format('m/d/Y');
$day = $mytime->format('l');
$thisDay = strtolower($day);
$offerWhen = $offer['offer_when'];
foreach(Offer::all() as $offerObject){
$offerObject->update(['offer_when' => 'tomorrow']);
$the_days = $offerObject['days'];
$offersAll = $offerObject::whereIn('days', array($the_days) )->orWhere('days', '=', array($the_days))->get();
return $offersAll;
}
}
The above query only returns one object with just 'tuesday' in it and not the one with an array that still has 'tuesday' in it.
The ideal scenario would be that it only ever shows results with the current day in the 'days' column. The current day is created with Carbon::now()->format('l');
I don't really understand everything in your code, but best approach here is to try with LIKE condition.
Try something like that:
->where('days', 'LIKE', '%' . $dayName . '%')
This will work here well because all day names are pretty different and none of them contains the other (like with big, bigger which would cause problems here).

traversing through javascript object using php

I am trying to print the values based on the key specified by the user..
My javascript object looks like
$test={
"timed_out": false,
"hits": {
"hits": [
{
"_index": "test2",
"_type": "news",
"_source": {
"partnerName": "Accountancy_Age",
"entityCount": 4,
"Categories": {
"Facets": [
{
"count": 1,
"entity": "Company",
"Company": [
{
"Pearson_Plc-Sponsored_Adr": [
{
"count": 1,
"entity": "Pearson"
}
],
"sector": "Communications",
"ticker": "PSO",
"entity": "Pearson Plc-Sponsored Adr",
"type": "ADR"
}
]
},
{
"CorporateAction": [
{
"count": 2,
"entity": "restructuring"
}
],
"count": 2,
"entity": "CorporateAction"
},
{
"count": 1,
"entity": "Persons",
"Persons": [
{
"count": 1,
"entity": "Steven Pearson"
}
]
}
]
},
"Title": "PwC takes on major London oil refinery administration ",
"Tags": "News",
"ParentUrl": "http://www.accountancyage.com/feeds/rss/maxcontentwords/75/category/business-regulation",
"Link": "http://www.accountancyage.com/aa/news/2141170/pwc-takes-major-london-oil-refinery-administration?WT.rss_f=Business+regulation&WT.rss_a=PwC+takes+on+major+London+oil+refinery+administration+",
"SourceName": "Accountancy_Age",
"SentimentResource": "neutral",
"Content": "<div class=\"article_description\" algoscore=\"83\">\n <p algoscore=\"34\"><strong>LONDON'S BIGGEST </strong>oil refinery has been handed over to administrators from PwC by its Swiss parent company.</p>\n <p algoscore=\"37\">Petroplus, which refines 220,000 barrels a day from the Thames, was declared insolvent after the group suffered refinancing issues, a high cost base and high restructuring costs.</p>\n <p algoscore=\"35\">The business has around 60 employees, and supplies aronud a fifth of London and the south-east's 2,000 forecourts.</p>\n <p algoscore=\"40\">"Our immediate priority is to continue to operate the Coryton refinery and the Teeside storage business, without disruption while the financial position is clarified and restructuring options are explored," said PwC joint administrator Steven Pearson.</p>\n <p algoscore=\"38\">"Over coming days we intend to commence discussions with a number of parties including customers, employees, the creditors and the government to secure the future of the Coryton and Teesside sites.</p>\n</div>"
}
},
{
"_index": "test3",
"_type": "news",
"_source": {
"partnerName": "propertyFile 7",
"entityCount": 33,
"Categories": {
"Types": {
"Facets": [
{
"count": 3,
"entity": "Company",
"Company": [
{
"sector": "Basic Materials",
"ticker": "BHP",
"entity": "Bhp Billiton Ltd-Spon Adr",
"Bhp_Billiton_Ltd-Spon_Adr": [
{
"count": 1,
"entity": "BHP Billiton Ltd"
}
],
"type": "ADR"
},
{
"sector": "Communications",
"ticker": "CHL",
"entity": "China Mobile Ltd-Spon Adr",
"type": "ADR",
"China_Mobile_Ltd-Spon_Adr": [
{
"count": 1,
"entity": "China Mobile"
}
]
},
{
"sector": "Energy",
"Royal_Dutch_Shell_Plc-Adr": [
{
"count": 1,
"entity": "Royal Dutch"
}
],
"ticker": "RDS/A",
"entity": "Royal Dutch Shell Plc-Adr",
"type": "ADR"
}
]
},
{
"count": 6,
"entity": "Country",
"Country": [
{
"region": "Asia",
"Taiwan": [
{
"count": 1,
"entity": "Taiwan"
}
],
"index": "TAIWAN TAIEX INDEX",
"entity": "Taiwan",
"currency": "Dollar (TWD)"
},
{
"region": "Latin Americas",
"index": "BRAZIL BOVESPA INDEX",
"Brazil": [
{
"count": 1,
"entity": "Brazil"
}
],
"entity": "Brazil",
"currency": "Real (BRL)"
},
{
"region": "East Europe",
"index": "ISE NATIONAL 100 INDEX",
"entity": "Turkey",
"Turkey": [
{
"count": 1,
"entity": "Turkey"
}
],
"currency": "Lira (TRY)"
},
{
"region": "Europe",
"index": "BLOOMBERG EUROPEAN 500 , Euro Stoxx 50 Pr",
"entity": "Europe",
"Europe": [
{
"count": 1,
"entity": "Europe"
}
],
"currency": "Euro (EUR)"
},
{
"region": "Asia",
"index": "CSI 300 INDEX , SHANGHAI SE COMPOSITE , SHENZHEN SE COMPOSITE IX , SSE COMPONENT STOCK IX",
"entity": "China",
"China": [
{
"count": 2,
"entity": "China"
}
],
"currency": "Yuan Renminbi (CNY)"
}
]
},
{
"AnalystLevel": [
{
"count": 1,
"entity": "Buy"
},
{
"count": 1,
"entity": "hold"
},
{
"count": 4,
"entity": "market"
}
],
"count": 6,
"entity": "AnalystLevel"
},
{
"MoneyEvent": [
{
"count": 1,
"entity": "Fund managers look at all sizes of companies and \r\nbase their selections on an index of companies that have paid at least $5 \r\nmillion in dividends over the past year."
}
],
"count": 1,
"entity": "MoneyEvent"
},
{
"DateEvent": [
{
"count": 1,
"entity": "CHICAGO, June 1 (Reuters) - Finding consistent total stock returns has \r\nalways been a challenge."
},
{
"count": 1,
"entity": "Many, if not most, of these funds, it should be noted, were touted last \r\nyear as part of a growing group of \"low-volatility\" stock funds."
},
{
"count": 1,
"entity": "The fund invests in companies \r\namong the top 100 dividend payers that have had payouts in the previous \r\nthree years."
},
{
"count": 1,
"entity": "Yet the insurer is \r\nthe top holding in the SPDR S&P International Dividend ETF , paying a 5.38 \r\npercent dividend yield as of June 1."
}
],
"count": 4,
"entity": "DateEvent"
},
{
"count": 5,
"LocationEvent": [
{
"count": 1,
"entity": "And some of the best sectors for high-dividend players are \r\nfar from Wall Street."
},
{
"count": 1,
"entity": "But even as the euro zone beast continues to flair \r\nits nostrils and U.S. employment wheezes, there are stocks that are worthy \r\ncontenders, particularly ones that pay dividends."
},
{
"count": 1,
"entity": "That's \r\nroughly twice the population of the U.S. already."
},
{
"count": 1,
"entity": "These funds can be volatile and will be impacted if more European countries \r\nslip into recession, the U.S. falters or the Eurozone banking crisis isn't \r\nresolved."
},
{
"count": 1,
"entity": "To find dividend players in emerging markets, I suggest the WisdomTree \r\nEmerging Markets Equity Income fund, which gives you exposure to China, \r\nBrazil, Taiwan and Turkey."
}
],
"entity": "LocationEvent"
},
{
"count": 3,
"CompanyEvent": [
{
"count": 1,
"entity": "China Mobile, the largest cellphone carrier in the People's \r\nRepublic, has more than 600 million subscribers - and is growing."
},
{
"count": 1,
"entity": "The Admiral Group, a U.K.-based \r\nauto insurance company, for example, is hardly in a league with the oil \r\nproducer Royal Dutch Shell in terms of name recognition."
},
{
"count": 1,
"entity": "Then you'd want a \r\ncompany like BHP Billiton Ltd. ), one of the world's largest natural \r\nresources companies."
}
],
"entity": "CompanyEvent"
},
{
"count": 1,
"entity": "AnalystAction",
"AnalystAction": [
{
"count": 1,
"entity": "Buy"
}
]
},
{
"count": 2,
"entity": "PercentEvent",
"PercentEvent": [
{
"count": 1,
"entity": "Europe's largest oil producer reported \r\nthat its earnings were up 11 percent in the first quarter."
},
{
"count": 1,
"entity": "Shell, by the way, is no slouch in the dividend department either, paying \r\n5.53 percent as of the same date."
}
]
},
{
"count": 1,
"entity": "Person",
"Person": [
{
"count": 1,
"entity": "John Wasik"
}
]
},
{
"count": 1,
"entity": "PersonEvent",
"PersonEvent": [
{
"count": 1,
"entity": "By John Wasik"
}
]
}
]
}
},
"Title": "Where in the world are dividends good?",
"ParentUrl": "http://feeds.reuters.com/reuters/blogs/JohnWasik?format=xml",
"Tags": "Blog",
"Link": "http://www.reuters.com/article/2012/06/01/column-wasik-worlddividends-idUSL1E8H15SF20120601?feedType=RSS&feedName=everything&virtualBrandChannel=11563",
"SourceName": "Reuters",
"SentimentResource": "positive",
"Content": "<span id=\"articleText\" algoscore=\"413\"><p></p><span class=\"focusParagraph\"></span><p>By John Wasik</p><p>CHICAGO, June 1 (Reuters) - Finding consistent total stock returns has always been a challenge. But even as the euro zone beast continues to flair its nostrils and U.S. employment wheezes, there are stocks that are worthy contenders, particularly ones that pay dividends. While they don't eliminate market risk, dividends can bolster total return in skittish equity markets. And some of the best sectors for high-dividend players are far from Wall Street.</p><p>For long-term investing, think commodities, energy, utilities and non-banking financial services. Banking is still touchy, but insurance is a safer bet.</p><p>Established, brand-name stocks often pay large dividends, but that doesn't mean they should dominate your portfolio. The Admiral Group, a U.K.-based auto insurance company, for example, is hardly in a league with the oil producer Royal Dutch Shell in terms of name recognition. Yet the insurer is the top holding in the SPDR S&P International Dividend ETF , paying a 5.38 percent dividend yield as of June 1.</p><p>Shell, by the way, is no slouch in the dividend department either, paying 5.53 percent as of the same date. Europe's largest oil producer reported that its earnings were up 11 percent in the first quarter.</p><p>The international dividend strategy is often rooted in sectors in which profits are consistent and growing. That translates into steady dividend growth year after year, although the sectors that are favored for stock-price appreciation will vary.</p><p>Let's say you were long in commodities, which isn't a bad play considering the demand for raw materials from developing countries. Then you'd want a company like BHP Billiton Ltd. ), one of the world's largest natural resources companies. BHP mines aluminum, copper, coal, iron ore, nickel, silver and uranium and also has oil and gas reserves.</p><p>Another growth sector is telecommunications, particularly in emerging economies. China Mobile, the largest cellphone carrier in the People's Republic, has more than 600 million subscribers - and is growing. That's roughly twice the population of the U.S. already.</p><p>A key part of the global dividend strategy is to stay in sectors that are likely to continue dividend growth. That's why exchange-traded funds make the most sense when investing in these companies. The funds can hold broad indexes of dividend payers so you don't have to guess which companies will maintain or raise their payouts. ETFs also blunt risk, since unusually high dividends can be a sign of a company's financial distress.</p><p>To find dividend players in emerging markets, I suggest the WisdomTree Emerging Markets Equity Income fund, which gives you exposure to China, Brazil, Taiwan and Turkey. Fund managers look at all sizes of companies and base their selections on an index of companies that have paid at least $5 million in dividends over the past year. An alternative is the SPDR S&P Emerging Markets Dividend ETF.</p><p>If you prefer a focus on more developed markets, then consider the iShares Dow Jones International Dividend Index ETF . The fund invests in companies among the top 100 dividend payers that have had payouts in the previous three years. A similar fund is the PowerShares International Dividend Achievers Portfolio.</p><p>Many, if not most, of these funds, it should be noted, were touted last year as part of a growing group of "low-volatility" stock funds. While I think that has been a misnomer because it implies that these vehicles won't be hit by general market declines - they certainly will - they deserve a place in your portfolio.</p><p>When selecting a global dividend-stock fund, keep in mind that they won't insulate you from market risk and they are not bond funds.</p><p>These funds can be volatile and will be impacted if more European countries slip into recession, the U.S. falters or the Eurozone banking crisis isn't resolved. They also are subject to sector risk. If they are over concentrated in say, energy, and that sector is sold off in a market correction, then you will see declines in share prices. Buy them to augment your current stock positions and to boost income, but they shouldn't be core holdings.</p></span>",
"ContentHash": 783187784,
"LinkObjects": {
"LinkObjects": [
{
"Link": "http://blogs.reuters.com/search/journalist.php?edition=us&n=john.wasik&",
"Object": "John Wasik"
}
]
}
}
}]}};
what Im trying to achieve here is that if the user specifies wordCount, then it should list out all the occurences of wordCount in the json.
My code looks like,
$.ajax({
url:"/elasticsearch-head/lib/es/queryManipulate.php",
type: 'POST',
datatype: 'json',
data: { index: _index_select, category: _field_select},
success:function(jsonQuery)
{
//alert(jsonQuery);
}
});
<?php
$index=$_POST["index"];
$selectCategory=$_POST["category"];
$url="http://localhost:9200/".$index."//_search";
$object=json_decode($_POST["field"]);
$fields=array();
$fields = explode(',',$selectCategory);
$results = array();
for ($from = 0; $from <50; $from+=10){
$object->from=$from;
$requestJSON=json_encode($object);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestJSON);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resultJSON= curl_exec($ch); // equivalent of our JSON string that Ive shown above
$resultObject = json_decode($resultJSON);
curl_close ($ch);
$hits = $resultObject->hits->hits;
$m=0;
for($j=0 ; $j < sizeOf($hits) ; $j++){
$result = array();
for($i=0 ; $i< sizeOf($fields) ; $i++){
if($fields[$i]=="Categories->Types->Facets")
{
$source = $hits[$j]->_source->Categories->Types->Facets;
//echo $m++ . ";" .sizeof($source)."<br>";
for($k=0; $k < sizeof($source); $k++)
{
//echo $fields[$i];
//echo json_encode($source[$k]->entity) ."<br><br>";
$result[$j]->{$fields[$i]} = json_encode($source[$k]->entity);
//echo $result[$j]->{$fields[$i]};
}
}
else
{
echo "test1";
$source = $hits[$j]->_source;
$result[$j]->{$fields[$i]} = json_encode($source->{$fields[$i]});
}
}
$results=array_merge($results,$result);
}
}
for($j=0 ; $j < sizeOf($fields) ; $j++) {
echo $fields[$j].",";
}
echo "<br>";
for($j=0 ; $j < sizeOf($results) ; $j++) {
$result = $results[$j];
$line="";
for($i=0 ; $i< sizeOf($fields) ; $i++){
#echo var_dump($result);
$field = $fields[$i];
$line.=$result->{$field}.",";
}
echo $line."<br>";
}
?>
This will work if the input is not array, if we give input an array say Company fpr exaample, and I want to output the items listed in that array, how am I gonna approach that?
Try something like this:
$output = null;
array_walk_recursive($array, "callback", $output);
function callback ($value, $key, &$output)
{
if ($key == 'wordCount')
{
$output .= $value;
}
}

Categories