Add values to array via foreach - php

I'm trying to add values to an array via foreach but it only returns the word "Array" not the actual strings.
$msg = array();
foreach ($results as $result) {
$inventory = $result->qoh;
$inventoryOrder = $result->qo;
$product = $result->item;
$totalinv = $inventory+$inventoryOrder;
if ($inventory <= $threshold) {
$message = "Inventory for $product has fallen beneath threshold. $inventory remaining.\n";
$msg[] = array($message);
}
}
print (array_values($msg));
I've tried a few different ways and everytime it returns the word "Array"

You should use print_r, not print. print is for stings only. Try this:
echo '<pre>'; print_r(array_values($msg)); echo '</pre>';

Use var_dump to see the values.
var_dump (array_values($msg));
var_dump will alway show you the type of the result too. Helps a lot in debugging. (Looking at your code, I'm assuming you are doing the same).

I think you need to change the following code:
$msg[] = array($message);
to
array_push($msg, $message);

Related

Parsing JSON in for each with increment PHP

I'm trying to parse a json file into a for each loop. The issue is the data is nested in containers with incremented numbers, which is an issue as I can't then just grab each value in the foreach. I've spent a while trying to find a way to get this to work and I've come up empty. Any idea?
Here is the json file tidied up so you can see what I mean - http://www.jsoneditoronline.org/?url=http://ergast.com/api/f1/current/last/results.json
I am trying to get values such as [number] but I also want to get deeper values such as [Driver][code]
<?php
// get ergast json feed for next race
$url = "http://ergast.com/api/f1/current/last/results.json";
// store array in $nextRace
$json = file_get_contents($url);
$nextRace = json_decode($json, TRUE);
$a = 0;
// get array for next race
// get date and figure out how many days remaining
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'][' . $a++ . '];
foreach ($nextRaceDate['data'] as $key=>$val) {
echo $val['number'];
}
?>
While decoding the json there's no need to flatten the object to an Associative array. Just use it how it is supposed to be used.
$nextRace = json_decode($json);
$nextRaceDate = $nextRace->MRData->RaceTable->Races[0]->Results;
foreach($nextRaceDate as $race){
echo 'Race number : ' . $race->number . '<br>';
echo 'Race Points : ' . $race->points. '<br>';
echo '====================' . '<br>';
}
CodePad Example
You are nearly correct with your code, you are doing it wrong when you try the $a++. Remove the $a = 0, you won't need it.
Till here you are correct
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results']
What you have to do next is this
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'];
foreach($nextRaceDate as $key => $value){
foreach($value as $key2 => $value2)
print_r($value2);
So, in my code, you are stopping at Results, and then, you want to iterate over all the results, from 0 to X, the first foreach will do that, you have to access $value for that. So, add another foreach to iterate over all the content that $value has.
There you go, I added a print_r to show you that you are iterating over what you wanted.
The problem is how you access to the elements in the nested array.
Here a way to do it:
$mrData = json_decode($json, true)['MRData'];
foreach($nextRace['RaceTable']['Races'] as $race) {
// Here you have access to race's informations
echo $race['raceName'];
echo $race['round'];
// ...
foreach($race['Results'] as $result) {
// And here to a result
echo $result['number'];
echo $result['position'];
// ...
}
}
I don't know where come's from your object, but, if you're sure that you'll get everytime one race, the first loop could be suppressed and use the shortcut:
$race = json_decode($json, true)['MRData']['RaceTable']['Races'][0];
Your problem is that the index must be an integer because the array is non associative. Giving a string, php was looking for the key '$a++', and not the index with the value in $a.
If you need only the number of the first race, try this way
$a = 0;
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'][$a];
echo "\n".$nextRaceDate['number'];
maybe you need to iterate in the 'Races' attribute
If you need all, try this way :
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races'];
foreach ($nextRaceDate as $key => $val) {
foreach ($val['Results'] as $val2) {
echo "\nNUMBER " . $val2['number'];
}
}

convert an array of arrays to json

i want to convert this array as shown below
array_countries=array("20"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"7","label"=>"Tanta"),
"21"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"1000","label"=>"Other"),
"22"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"0","label"=>"All"),
"23"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"1","label"=>"Ahmedabad"));
into this format:
"3":{"Egypt":{"7":Tanta,"1000":"other"}},"80":{"India":{"0":"All","1":Ahmedabad}}
I am using PHP and not able to figure out how can i do this. I have used json_encode. but the results are not correct.I am using PHP as my language.
thanks in advance
Before converting into json, you should change the array:
$array_countries_formated = array();
foreach ($array_countries as $item)
{
$array_countries_formated[$item['cntryValue']][$item['cntryLabel']][$item['value']] = $item['label'];
}
echo $array_countries_formated = json_encode($array_countries_formated, JSON_FORCE_OBJECT);
Result:
{"3":{"Egypt":{"7":"Tanta","1000":"Other"}},"80":{"India":{"0":"All","1":"Ahmedabad"}}}
Try this...
<?php
$array_countries=array("20"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"7","label"=>"Tanta"),
"21"=>array("cntryValue"=>"3","cntryLabel"=>"Egypt","value"=>"1000","label"=>"Other"),
"22"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"0","label"=>"All"),
"23"=>array("cntryValue"=>"80","cntryLabel"=>"India","value"=>"1","label"=>"Ahmedabad"));
$jsonString = json_encode($array_countries);
print_r($jsonString);
?>
Result:
{"20":{"cntryValue":"3","cntryLabel":"Egypt","value":"7","label":"Tanta"},"21":{"cntryValue":"3","cntryLabel":"Egypt","value":"1000","label":"Other"},"22":{"cntryValue":"80","cntryLabel":"India","value":"0","label":"All"},"23":{"cntryValue":"80","cntryLabel":"India","value":"1","label":"Ahmedabad"}}
If I understand your requested output correctly, the following should do the trick:
$result = array();
foreach ($array_countries as $country) {
$cntryValue = $country["cntryValue"];
if (!array_key_exists($cntryValue, $result)) {
$result[$cntryValue] = array();
}
$result[$cntryValue][$country["cntryLabel"]] = array();
$result[$cntryValue][$country["cntryLabel"]][$country["value"]] = $country["label"];
}
echo json_encode($result) . "\n";
A little explanation: the array provided ($array_countries) is formatted differently as compared to your requested output. Therefore, it should be converted. That is what the foreach loop does. The formatted result can be converted to json using the json_encode function.

Unable to ECHO PostgreSQL Query Results - PHP

I've successfully connected to a PostgreSQL database and even the query is running successfully.
But when I try to print the data using this code echo $data I get error as Array to String Conversion.
Tried searching in the forum and google. Nothing was fruitful.
Please help me.
Code used to convert it to array and print it.
if ( ! $myquery ) {
echo pg_error();
die;
}
$data = array();
for ($x = 0; $x < pg_num_rows($myquery); $x++) {
$data[] = pg_fetch_assoc($myquery);
}
// echo json_encode($data);
// $data2 = array_shift($data);
echo $data;
pg_close($server);
Read the error :
Array to String Conversion
Try to display it using var_dump or print_r because it's an array.
The error says that you want to display an array with echo which can only display string.
exemple : var_dump($data);
To just print the array (for debuging) use var_dump() like this:
var_dump($data)
But if you want to echo every line in the array you have to loop:
foreach ($data as $row) {
echo $row;
}
You are pinting array with echo.Try print_r(); that will print array. Like this print_r($data);
Try using var_dump($var) or print_r($var) functions

Accessing an array in an object

If i knew the correct terms to search these would be easy to google this but im not sure on the terminology.
I have an API that returns a big object. There is one particular one i access via:
$bug->fields->customfield_10205[0]->name;
//result is johndoe#gmail.com
There is numerous values and i can access them by changing it from 0 to 1 and so on
But i want to loop through the array (maybe thats not the correct term) and get all the emails in there and add it to a string like this:
implode(',', $array);
//This is private code so not worried too much about escaping
Would have thought i just do something like:
echo implode(',', $bug->fields->customfield_10205->name);
Also tried
echo implode(',', $bug->fields->customfield_10205);
And
echo implode(',', $bug->fields->customfield_10205[]->name);
The output im looking for is:
'johndoe#gmail.com,marydoe#gmail.com,patdoe#gmail.com'
Where am i going wrong and i apologize in advance for the silly question, this is probably so newbie
You need an iteration, such as
# an array to store all the name attribute
$names = array();
foreach ($bug->fields->customfield_10205 as $idx=>$obj)
{
$names[] = $obj->name;
}
# then format it to whatever format your like
$str_names = implode(',', $names);
PS: You should look for attribute email instead of name, however, I just follow your code
use this code ,and loop through the array.
$arr = array();
for($i = 0; $i < count($bug->fields->customfield_10205); $i++)
{
$arr[] = $bug->fields->customfield_10205[$i]->name;
}
$arr = implode(','$arr);
This is not possible in PHP without using an additional loop and a temporary list:
$names = array();
foreach($bug->fields->customfield_10205 as $v)
{
$names[] = $v->name;
}
implode(',', $names);
You can use array_map function like this
function map($item)
{
return $item->fields->customfield_10205[0]->name;
}
implode(',', array_map("map", $bugs)); // the $bugs is the original array

It is not ouputting values in array when echoed

I think there is a problem when I echo $whereArray and orderByArray. If I type in a word such as "Question" and then submit it, I expect it to display in the echos "%".Question."%"; for both arrays. But instead in both echos it just displays "Array" for both echos. Does this mean that both arrays are not working when it comes to storing in the values?
$searchquestion = $_GET['questioncontent'];
$terms = explode(" ", $searchquestion);
$whereArray = array();
$orderByArray = array();
//loop through each term
foreach ($terms as $each) {
$i++;
$whereArray[] = "%".$each."%";
$orderByArray[] = "%".$each."%";
}
echo $whereArray;
echo $orderByArray;
echo() only works for strings. PHP converts your array to "Array" as a fallback.
When you're debugging, you should use var_dump(). It will tell you the type of the object and its content.
Use var_dump or print_r instead of echo (they are functions, not constructs like echo is).
An array needs to be printed out using a special function such as print_r. If you want to print out a value in your array try:
echo $whereArray[0];
To get the first element. Be careful because if the array is empty you will get an error.
you can also loop through them
foreach($arrayname as $value)
echo $value;
or
echo implode("",$arrayname);

Categories