PHP global variable shows null for first iteration of loop - php

Sorry couldn't frame a better title.
So here's the problem
I have a function inside functions.php
function show_news(){
$id_counter = 1;
$json_news = array(
"id" => 0,
"title" => ""
);
$json_o = json_decode(file_get_contents(JSON_DATA_FOLDER.'news.json'));
foreach ($json_o as $id => $news_category)
{
echo '<h2>'.$id.'<h2>';
foreach ($news_category as $news)
{
if(IsNullOrEmptyString($news->id)){$json_news['id'] = $id_counter; $id_counter++;}
else{$json_news['id']=$news->id;}
if(!IsNullOrEmptyString($news->title)){$json_news['title']=$news->title;}
var_dump($json_news);
echo "<br/>-------<br/>";
include('news-layout.php');
}
}
}
I'm reading a json file and for each element I am assigning its value to an array.
Then I'm including 'news-layout.php'. For testing purposes I've kept just these 3 lines of code inside 'news-layout.php'
<?php
global $json_news;
var_dump($json_news);
echo"<br/>=======================<hr/>";
?>
So I'm doing a var_dump inside my function as well as on the included page. But I'm getting strange result. Everything works fine except that var_dump($json_news) on included page shows NULL for first iteration of loop !!
Here's the output
todays_specials
array(2) { ["id"]=> int(1) ["title"]=> string(26) "Okie Since I have to do it" }
-------
NULL
=======================
array(2) { ["id"]=> int(2) ["title"]=> string(16) "Vegetable Samosa" }
-------
array(2) { ["id"]=> int(2) ["title"]=> string(16) "Vegetable Samosa" }
=======================
array(2) { ["id"]=> int(3) ["title"]=> string(16) "Vegetable Pakora" }
-------
array(2) { ["id"]=> int(3) ["title"]=> string(16) "Vegetable Pakora" }
=======================
You can see that strange NULL coming there.
Can anyone explain what's happening or how to fix it?

Your $json_news var is local to the functions file first. Then the layout file is included and you create the global $json_news var, and from then on the global is used. Set it to global in your functions file and remove the variable declaration in the layout file and you should be good to go!
Like this:
function show_news(){
$id_counter = 1;
global $json_news = array(
"id" => 0,
"title" => ""
);
$json_o = json_decode(file_get_contents(JSON_DATA_FOLDER.'news.json'));
foreach ($json_o as $id => $news_category){
echo '<h2>'.$id.'<h2>';
foreach ($news_category as $news){
if(IsNullOrEmptyString($news->id)){
$json_news['id'] = $id_counter; $id_counter++;
}else{
$json_news['id']=$news->id;
}
if(!IsNullOrEmptyString($news->title)){
$json_news['title']=$news->title;
}
var_dump($json_news);
echo "<br/>-------<br/>";
include('news-layout.php');
}
}
}
'news-layout.php'
<?php
var_dump($json_news);
echo"<br/>=======================<hr/>";
?>
Side note: using globals like that is not to be recommended!

Related

PHP Arrays - Merge two arrays where a value is added together

I need some more help regarding PHP Arrays and the issue I am having. I have an array like this: -
array(2) {
[0]=>
array(2) {
[0]=>
array(2) {
["count"]=>
string(3) "100"
["id"]=>
int(46)
}
[1]=>
array(2) {
["count"]=>
string(3) "300"
["id"]=>
int(53)
}
}
[1]=>
array(1) {
[0]=>
array(2) {
["count"]=>
string(3) "200"
["id"]=>
int(46)
}
}
}
However, I would like it to look more like this as array: -
array(2) {
[0]=>
array(2) {
["count"]=>
string(3) "300" <--- This has been added from Array 1 and 2
["id"]=>
int(46)
}
[1]=>
array(2) {
["count"]=>
string(3) "300"
["id"]=>
int(53)
}
}
Basically if the same id is in both areas I want the count number to be added to each other but if it's not then it needs to just be left alone and included in the array.
I have used a number of array functions such as array_merge and array_push but I am running out of ideas of how this could work. I have also started working on a foreach with if statements but I just got myself completely confused. I just need a second pair of eyes to look at the issue and see howe it can be done.
Thanks again everyone.
Should work with something like this:
$idToCountArray = array(); //temporary array to store id => countSum
array_walk_recursive($inputArray, function($value,$key) { //walk each array in data structure
if(isset(value['id']) && isset($value['count'])) {
//we have found an entry with id and count:
if(!isset($idToCountArray[$value['id']])) {
//first count for id => create initial count
$idToCountArray[$value['id']] = intval($value['count']);
} else {
//n'th count for id => add count to sum
$idToCountArray[$value['id']] += intval($value['count']);
}
}
});
//build final structure:
$result = array();
foreach($idToCountArray as $id => $countSum) {
$result[] = array('id' => $id, 'count' => ''.$countSum);
}
Please note that I have not testet the code and there is probably a more elegant/performant solution.
You could use something like this:
$end_array = array();
function build_end_array($item, $key){
global $end_array;
if (is_array($item)){
if( isset($item["id"])){
if(isset($end_array[$item["id"]]))
$end_array[$item["id"]] = $end_array[$item["id"]] + $item["count"]*1;
else
$end_array[$item["id"]] = $item["count"]*1;
}
else {
array_walk($item, 'build_end_array');
}
}
}
array_walk($start_array, 'build_end_array');
Here is a fiddle.
Thank you ever so much everyone. I actually worked it by doing this: -
$fullArray = array_merge($live, $archive);
$array = array();
foreach($fullArray as $key=>$value) {
$id = $value['id'];
$array[$id][] = $value['count'];
}
$result = array();
foreach($array as $key=>$value) {
$result[] = array('id' => $key, 'count' => array_sum($value));
}
return $result;

How to add data to OBJECT from Wordpress get_results in PHP

Seems really easy, but I can't seem to figure it out...
I have a simple line that gets mysql results through wordpress like this:
$sql_results = $wpdb->get_results($sql_phrase);
Then I parse it as JSON and echo it: json_encode($sql_results);
However, I want to add other data before I parse it as JSON. But I'm not sure how.
$sql_results basically gets me a list of post ID's, title and category.
It looks like this in var_dump (this is just the first row):
array(1)
{
[0]=> object(stdClass)#2737 (7)
{
["ID"]=> string(4) "2700"
["post_title"]=> string(18) "The compact helmet"
["category"]=> string(5) "Other"
}
}
Now to start with something easy, I'd like all associative arrays inside the object to have the extra key-value. I tried the following but got an error:
500 Internal error.
foreach($sql_search as $key => $value)
{
$value['pic_img'] = "test";
$sql_search[$key]=$value;
}
$result=$sql_search;
$sql_results = array(1)
{
[0]=> object(stdClass)#2737 (7)
{
["ID"]=> string(4) "2700"
["post_title"]=> string(18) "The compact helmet"
["category"]=> string(5) "Other"
}
}
foreach($sql_results as $key=>$value)
{
$value->solution = 'good';
$sql_results[$key]=$value;
}
$result=$sql_results;
var_dump($result);
$test = array ( array("ID"=>"35", "name"=>"Peter", "age"=>"43"),
array("ID"=>"34", "name"=>"James", "age"=>"19"), array("ID"=>"31", "name"=>"Joe", "age"=>"40") );
foreach($test as $key=>$value)
{
$value['solution'] = 'good';
$test[$key]=$value;
}
$result=$test;
var_dump($result);

PHP - array_push is replacing instead of add to SESSION Variable

<?php
session_start();
$pid = $_GET['pid'];
$ptype = $_GET['ptype'];
$_SESSION = array();
$_SESSION['cart_items'] = array();
if (isset($_GET['add_cart']) && !empty($_GET['add_cart'])) {
// Add new data to Session var
$newdata = array($pid , $ptype, 1 );
array_push($_SESSION['cart_items'], $newdata);
}
echo '<pre>';
var_dump($_SESSION);
echo '</pre>';
?>
array_push replaces the data already in the $_SESSION with $newdata variable in the $_SESSION instead of adding it.
For example:
I enter the url: ?pid=1&ptype=CH-&add_cart=Add+to+Cart
And the array looks like this:
array(1) {
["cart_items"]=>
array(1) {
[0]=>
array(3) {
[0]=>
string(1) "1"
[1]=>
string(3) "CH-"
[2]=>
int(1)
}
}
}
That's great. But when I enter another url like: ?pid=1&ptype=CPU-&add_cart=Add+to+Cart
The array looks like this:
array(1) {
["cart_items"]=>
array(1) {
[0]=>
array(3) {
[0]=>
string(1) "1"
[1]=>
string(4) "CPU-"
[2]=>
int(1)
}
}
}
instead of this:
array(1) {
["cart_items"]=>
array(1) {
[0]=>
array(3) {
[0]=>
string(1) "1"
[1]=>
string(3) "CH-"
[2]=>
int(1)
}
[1]=>
array(3) {
[0]=>
string(1) "1"
[1]=>
string(4) "CPU-"
[2]=>
int(1)
}
}
}
It replaces the data that was already in the Session. I want it to add to it. How do I do so?
Thanks in advance!
change lines 5&6 from
$_SESSION = array();
$_SESSION['cart_items'] = array();
to
// $_SESSION = array();
// $_SESSION['cart_items'] = array();
array_push wasn't clearing your data. those two lines were clearing your session data on every page load.

PHP & JSON: How can I get a value from where another value equals xyz?

I'm receiving a JSON and trying to interpret some values using PHP.
Example snippet from a JSON dump:
["11811"]=>
object(stdClass)#15 (11) {
["parent_area"]=>
NULL
["generation_high"]=>
int(19)
["all_names"]=>
object(stdClass)#16 (0) {
}
["id"]=>
int(11811)
["codes"]=>
object(stdClass)#17 (3) {
["ons"]=>
string(2) "08"
["gss"]=>
string(9) "E15000008"
["unit_id"]=>
string(5) "41421"
}
["name"]=>
string(10) "South East"
["country"]=>
string(1) "E"
["type_name"]=>
string(15) "European region"
["generation_low"]=>
int(1)
["country_name"]=>
string(7) "England"
["type"]=>
string(3) "EUR"
}
As there is lots of (nested) data, I need to obtain the value of ["name"] where ["type_name"] == 'European region'.
Thanks.
You could use array_filter()
$data_array = array(...);
function is_european($data) {
return $data->type_name == 'European region';
}
$filtered = array_filter($data_array,'is_european');
And then use filtered array to obtain values.
Maybe a better way would be to use JsonPath, like this, assuming your array is a result of decoding JSON (object):
$names = jsonPath($data_object, "$.[?(#['type_name'] == 'European region')].name");
Haven't tried this myself, it may need a bit of correction.
Try this:
<?php
$json = JSON_decode(str,true);
$arr = Array();
foreach($json as $f) {
/* eg. $f = $json["11811"] */
if($f['type_name'] == 'European region') {
$arr[] = $f['name'];
}
}
?>

PHP: help with array structure

My last question helped me get data from a form into an array. The array is fairly different in structure to anything I've used before. I have multiple records with a textbox and checkbox each. Here is the form data:
array(4) {
["product"]=> array(4) {
[0]=> string(5) "Dummy"
[1]=> string(7) "Dummy 2"
[2]=> string(7) "Dummy 3"
[3]=> string(7) "Dummy 4"
}
["tags"]=> array(4) {
[0]=> string(25) "#enter, #product, #hastag"
[1]=> string(0) ""
[2]=> string(25) "#enter, #product, #hastag"
[3]=> string(25) "#enter, #product, #hastag"
}
["chk"]=> array(2) {
[0]=> string(2) "on"
[2]=> string(2) "on"
}
["submit"]=> string(5) "tweet"
}
I want to get the data from this array into a form such as (only if chk = "on"):
tweet[0]["product"] = "dummy"
tweet[0]["tag"] = "hash tag list here"
tweet[1]["product"] = "dummy3"
tweet[1]["tag"] = "hash tag list here"
Any help most appreciated! :)
First I'd recommend using 1 instead of on. You should try to use numerical values whenever possible as they require less processing. I think you need to readjust your HTML, so you don't do any processing on the PHP side at all...
<input type="checkbox" name="tweet[(YOUR_TWEET_ID)][product]" value="PRODUCT_NAME"/>
<input type="text" name="tweet[(YOUR_TWEET_ID)][tags]" value=""/>
This will cause the form to $_POST exactly how you want it without any additional code.
update
foreach ($_POST['tweet'] as $tweetId => $value) {
//again, it'd be a good idea to use a numerical value here
if (strlen($value['product']) > 0) {
//this tweet was checked, lets do with it what we need
//here's how you'd get the tags
echo $_POST['tweet'][$tweetId]['tags'];
}
}
$finalArray = array();
foreach($array['product'] as $key => $name){
if(!empty($array['chk'][$key])){
$finalArray[] = array(
"product" => $name,
"tag" => $array['tags'][$key]);
};
}
Pretty simple:
$i=0;
foreach ($array['chk'] as $key => $val) {
if ($val == "on") {
$new_array[$i]['product'] = $array['product'][$key];
$new_array[$i++]['tags'] = $array['tags'][$key];
}
}
print_r($new_array);
Should do it, there are other ways, this is just one of them.
foreach ($records['chk'] as $id => $temp) {
$tweet[$id]['product'] = $records['product'][$id];
$tweet[$id]['tag'] = $records['tags'][$id];
}

Categories