Faster way of doing this? - php

I have the following code, but it runs the foreach loop one at a time. Is there a way of making them all run at once?
foreach($json['orders']['cnr_output_ship_to_header'] as $header)
{
$orders_array[] = $header;
$guests_array[] = $header['guests']['cnr_output_guest_detail'];
$items_array[] = $header['items']['cnr_output_item_detail'];
}
foreach($guests_array as $guests)
{
pdo_insert('cnr_output_guest_detail', (array)$guests);
}
foreach($items_array as $items)
{
pdo_insert('cnr_output_item_detail', (array)$items);
}
foreach($orders_array as $orders)
{
pdo_insert('cnr_output_ship_to_header', (array)$orders);
}

This should work just fine
foreach ( $json['orders']['cnr_output_ship_to_header'] as $header ) {
pdo_insert('cnr_output_guest_detail', (array) $header['guests']['cnr_output_guest_detail']);
pdo_insert('cnr_output_item_detail', (array) $header['items']['cnr_output_item_detail']);
pdo_insert('cnr_output_ship_to_header', (array) $header);
}

why not this:
foreach($json['orders']['cnr_output_ship_to_header'] as $header) {
//$orders_array[] = $header;
pdo_insert('cnr_output_ship_to_header', (array)$header);
//$guests_array[] = $header['guests']['cnr_output_guest_detail'];
pdo_insert('cnr_output_guest_detail', (array)$header['guests']['cnr_output_guest_detail']);
//$items_array[] = $header['items']['cnr_output_item_detail'];
pdo_insert('cnr_output_item_detail', (array)$header['items']['cnr_output_item_detail']);
}

Related

Invalid argument supplied for foreach() inside if else PHP [duplicate]

Why am I getting this PHP Warning?
Invalid argument supplied for foreach()
Here is my code:
// look for text file for this keyword
if (empty($site["textdirectory"])) {
$site["textdirectory"] = "text";
}
if (file_exists(ROOT_DIR.$site["textdirectory"].'/'.urlencode($q).'.txt')) {
$keywordtext =
file_get_contents(ROOT_DIR.$site["textdirectory"].'/'.urlencode($q).'.txt');
}
else {
$keywordtext = null;
}
$keywordsXML = getEbayKeywords($q);
foreach($keywordsXML->PopularSearchResult as $item) {
$topicsString = $item->AlternativeSearches;
$relatedString = $item->RelatedSearches;
if (!empty($topicsString)) {
$topics = split(";",$topicsString);
}
if (!empty($relatedString)) {
$related = split(";",$relatedString);
}
}
$node = array();
$node['keywords'] = $q;
2
$xml = ebay_rss($node);
$ebayItems = array();
$totalItems = count($xml->channel->item);
$totalPages = $totalItems / $pageSize;
$i = 0;
foreach ($xml->channel->item as $item) {
$ebayRss =
$item->children('http://www.ebay.com/marketplace/search/v1/services');
if ($i>=($pageSize*($page-1)) && $i<($pageSize*$page)) {
$newItem = array();
$newItem['title'] = $item->title;
$newItem['link'] = buyLink($item->link, $q);
$newItem['image'] = ebay_stripImage($item->description);
$newItem['currentbid'] = ebay_convertPrice($item->description);
$newItem['bidcount'] = $ebayRss->BidCount;
$newItem['endtime'] = ebay_convertTime($ebayRss->ListingEndTime);
$newItem['type'] = $ebayRss->ListingType;
if (!empty($ebayRss->BuyItNowPrice)) {
$newItem['bin'] = ebay_convertPrice($item->description);
}
array_push($ebayItems, $newItem);
}
$i++;
}
$pageNumbers = array();
for ($i=1; $i<=$totalPages; $i++) {
array_push($pageNumbers, $i);
}
3
// get user guides
$guidesXML = getEbayGuides($q);
$guides = array();
foreach ($guidesXML->guide as $guideXML) {
$guide = array();
$guide['url'] = makeguideLink($guideXML->url, $q);
$guide['title'] = $guideXML->title;
$guide['desc'] = $guideXML->desc;
array_push($guides,$guide);
}
What causes this warning?
You should check that what you are passing to foreach is an array by using the is_array function
If you are not sure it's going to be an array you can always check using the following PHP example code:
if (is_array($variable)) {
foreach ($variable as $item) {
//do something
}
}
This means that you are doing a foreach on something that is not an array.
Check out all your foreach statements, and look if the thing before the as, to make sure it is actually an array. Use var_dump to dump it.
Then fix the one where it isn't an array.
How to reproduce this error:
<?php
$skipper = "abcd";
foreach ($skipper as $item){ //the warning happens on this line.
print "ok";
}
?>
Make sure $skipper is an array.
Because, on whatever line the error is occurring at (you didn't tell us which that is), you're passing something to foreach that is not an array.
Look at what you're passing into foreach, determine what it is (with var_export), find out why it's not an array... and fix it.
Basic, basic debugging.
Try this.
if(is_array($value) || is_object($value)){
foreach($value as $item){
//somecode
}
}

PHP - recursive function foreach

I would to create a recursive function in order to retrieve data from an array and to organize then.
However I have some difficulties to create the right logic. The principle must be apply to any sub level until it ends or nothing is found.
I want to prevent this kind of code by repeating a foreach inside a foreach...:
$cats = get_categories($args);
$categories = array();
foreach($cats as $cat){
$parent = $cat->category_parent;
if ($parent) {
$categories['child'][$parent][$cat->cat_ID] = $cat->name;
} else {
$categories['parent'][$cat->cat_ID] = $cat->name;
}
}
}
if (isset($categories['parent']) && !empty($categories['parent'])) {
foreach($categories['parent'] as $id => $cat){
$new_cats[$id]['title'] = $cat;
if (isset($categories['child'][$id])) {
foreach($categories['child'][$id] as $child_id => $child_cat){
$new_cats[$child_id]['title'] = $child_cat;
$new_cats[$child_id]['parent_id'] = $id;
if (isset($categories['child'][$child_id])) {
foreach($categories['child'][$child_id] as $sub_child_id => $sub_child_cat){
$new_cats[$sub_child_id]['title'] = $sub_child_cat;
$new_cats[$sub_child_id]['parent_id'] = $child_id;
}
}
}
}
}
}
}
May be this code help you to get idea for formatting your desired array format.
<?php
// Main function
function BuildArr($arr)
{
$formattedArr = array();
if(!empty($arr))
{
foreach($arr as $val)
{
if($val['has_children'])
{
$returnArr = SubBuildArr($val['children']); // call recursive function
if(!empty($rs))
{
$formattedArr[] = $returnArr;
}
}
else
{
$formattedArr[] = $val;
}
}
}
return $formattedArr;
}
// Recursive Function( Build child )
function SubBuildArr($arr)
{
$sub_fortmattedArr = array();
if(!empty($arr))
{
foreach($arr as $val)
{
if($val['has_children'])
{
$response = SubBuildArr($val['children']); // call recursive
if(!empty($response))
{
$sub_fortmattedArr[] = $response;
}
}
else
{
$sub_fortmattedArr[] = $arr;
}
}
return $sub_fortmattedArr;
}
}
?>
I use this code for my previous project for generating categories that upto n-th level

How to remove "#attributes" when using simplexml_load_string() to convert XML to JSON

What I need is,
but what i got is,
How can I remove "#attributes" from the result.
The below code works for me:
// Cleans up ugly JSON data by removing #attributes tag
function cleanup_json ($ugly_json) {
if (is_object($ugly_json)) {
$nice_json = new stdClass();
foreach ($ugly_json as $attr => $value) {
if ($attr == '#attributes') {
foreach ($value as $xattr => $xvalue) {
$nice_json->$xattr = $xvalue;
}
} else {
$nice_json->$attr = cleanup_json($value);
}
}
return $nice_json;
} else if (is_array($ugly_json)) {
$nice_json = array();
foreach ($ugly_json as $n => $e) {
$nice_json[$n] = cleanup_json($e);
}
return $nice_json;
} else {
return $ugly_json;
}
}
// Convert XML to JSON
function convert_to_json ($xml_string) {
$xml = simplexml_load_string($xml_string);
$ugly_json = json_decode(json_encode($xml));
$nice_json = cleanup_json($ugly_json);
return json_encode($nice_json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
}
Try this. It may work for you.
$xml = simplexml_load_string($string);
$json = json_encode($xml, true);

Recursive php menu

I have been searching around for some time but cannot seem to find an answer to my problem.
I have a deep nested array that I need to turn into a nested menu.
https://gist.github.com/anonymous/98e0dcf4f2aef40a1da6
I would like it to end up as something like the following.
https://gist.github.com/anonymous/a0dd4c7d047f11a5ce82
class foo {
function NavigationBuild($routes, $child = false) {
if ($child) {
foreach($routes as $route = > $row) {
if (is_array($row['children'])) {
$output. = self::NavigationBuild($row['children'], true);
} else {
$output. = "<li>".$val['route']."MEEEEE</li>";
}
}
} else {
$output. = '<ul>';
foreach($routes as $route = > $row) {
if (!strlen($row['parent'])) {
$output. = "<li>".$route."</li>";
}
foreach($row['children'] as $key = > $val) {
if (is_array($val['children'])) {
$output. = self::NavigationBuild($val['children'], true);
} else {
$output. = "<li>".$val['route']."MEEEEE</li>";
}
}
}
$output. = '</ul>';
}
return $output;
}
}
Figured it out - seems some sleep was needed.
Thanks to all USEFUL input

Looping through Facebook JSON object

I am currently getting the output I desire, although It seems that the only way I can get this to work is with these nasty nested foreach loops. I know that there must be a better way to loop this this JSON object.
$json = 'https://graph.facebook.com/218894654822767_609825405729688?fields=id,likes&key=value&access_token=245675758812857%7Ca2b43c96b8f2db07561ac8f6054b2632';
$fbObject = file_get_contents($json);
$array = json_decode($fbObject, true);
$count = 0;
if(is_array($array))
{
foreach ($array as $key => $object) {
if(is_array($object))
{
foreach ($object as $likes){
if(is_array($likes))
{
foreach ( $likes as $data ){
if(is_array($data))
{
foreach ( $data as $id ){
if (is_numeric($id))
{
echo "$id".'<br />';
}
}
}
}
}
}
}
}
}
?>
Simplifying:
$json_url = 'https://graph.facebook.com/218894654822767_609825405729688?fields=id,likes&key=value&access_token=245675758812857%7Ca2b43c96b8f2db07561ac8f6054b2632';
$json = json_decode(file_get_contents($json_url));
$user_ids = array();
foreach ($json->likes->data as $user) {
$user_ids[] = $user->id;
}
print implode('<br />', $user_ids);
Simplifying even more:
$json_url = 'https://graph.facebook.com/218894654822767_609825405729688?fields=id,likes&key=value&access_token=245675758812857%7Ca2b43c96b8f2db07561ac8f6054b2632';
$json = json_decode(file_get_contents($json_url));
print implode('<br />', array_map(function ($user) {
return $user->id;
}, (array) $json->likes->data));
That's all! :)

Categories