displaying multidimensional array - php

How do you display the output of a 2 dimensional arrays
Here's the code:
I know how to display both of them separately doing.
foreach($Father as $value){
echo $value[0] . " " . $value[1] . "<br />";
}
foreach($Son as $value){
echo $value[0] . " " . $value[1] . "<br />";
}

try this - it assumes that each father has exactly 1 son though
$i = 0;
foreach($Father as $value){
echo $value[0] . " " . $value[1] . "<br />";
echo "-" . $Son[$i][0] . " " . $Son[$i][1] . "<br />";
$i += 1;
}

Related

PHP: how to make a sum inside a "for each" cycle?

I've made a foreach loop that print some variables found in an xml file:
foreach ($xml->result->rowset->row as $row)
{
echo $row["price"] . " " . $row["product"] . "</br>";
}
I would like to get the sum of all the "prices" shown. How can i do?
Just have a variable add up those values as you iterate:
$total = 0; // start with zero
foreach ($xml->result->rowset->row as $row)
{
$total += $row["price"]; // add price to total
echo $row["price"] . " " . $row["product"] . "</br>";
}
echo $total; // echo out total amount
Store the count in a variable:
$total = 0;
foreach ($xml->result->rowset->row as $row) {
echo $row["price"] . " " . $row["product"] . "</br>";
$total += $row['price']; // assumed row_price is some integer
}
echo $total;
Simply add it to a new variable:
$sum = 0;
foreach ($xml->result->rowset->row as $row) {
echo $row["price"] . " " . $row["product"] . "<br />";
$sum += $row["price"];
}
echo $sum . "<br />";
$sum = 0;
foreach ($xml->result->rowset->row as $row)
{
echo $row["price"] . " " . $row["product"] . "</br>";
$sum += $row["price"] ;
}
echo $sum ;
isnt that simple ?
$sum=0;
foreach ($xml->result->rowset->row as $row)
{
echo $row["price"] . " " . $row["product"] . "</br>";
$sum +=$row["price"];
}
echo $sum;
just try this code!!

Multidimensional array loop not displaying the result for objects

I am getting the result from the SOAP client as an response. I just have to analyze the structure of the parameter and display the results accordingly. I have the following srucutre for SerialEquipment and i am getting the results peoperly for all the parameters except the Esaco parameter. The Esaco parameter is an array object and it resides inside the SerialEquipment array. I am trying to fetch the response from Esaco array object but getting an error as Invalid arguments supplied for foreach. I am not understanding how to get the results for Esaco Parameter by looping properly.Just a small mistake i am doing in looping the array.
Code:
foreach($Serial as $key => $obj)
{
echo "<b>"."Serial Equipment=>" . $key . "</b>"."<br>";
echo "Code=>". $obj->Code . "<br>";
echo "Desc Short=>". $obj->Desc_Short . "<br>";
echo "Desc Long=>". $obj->Desc_Long . "<br>";
foreach($obj->Esaco as $key2 => $obj2)
{
if($obj2 === null){
// doesn't contain Esaco
break;
}
else{
echo "<b>"."Esaco=>" . $key2 . "</b>"."<br>";
echo "EsacoMainGroupCode=>". $obj2->EsacoMainGroupCode . "<br>";
echo "EsacoMainGroupDesc=>". $obj2->EsacoMainGroupDesc . "<br>";
echo "EsacoSubGroupCode=>". $obj2->EsacoSubGroupCode . "<br>";
echo "EsacoSubGroupCode=>". $obj2->EsacoSubGroupDesc . "<br>";
echo "EsacoSubGroupCode=>". $obj2->EsacoGroupCode . "<br>";
echo "EsacoSubGroupCode=>". $obj2->EsacoGroupDesc . "<br>";
}
}
}
if($parameter['aktion'] == 'getVehicle')
{
$vehicle = getVehicleValuation();
$Serial=$vehicle['SerialEquipment'];
$VehicleFuel=$vehicle['VehicleFuel'];
foreach($VehicleFuel as $key => $obj2)
{
echo "Fuel Type=>". $obj2->Fuel_Type . "<br>";
echo "Fuel Type Code=>". $obj2->Fuel_Type_Code . "<br>";
echo "ECE_Unit=>". $obj2->ECE_Unit . "<br>";
echo "ECE_In=>". $obj2->ECE_In . "<br>";
echo "ECE_Out=>". $obj2->ECE_Out . "<br>";
echo "ECE_All=>". $obj2->ECE_All . "<br>";
echo "ECE_CO2=>". $obj2->ECE_CO2 . "<br>";
}
}
This is my structure for SerialEquipment:
if($parameter['aktion'] == 'getVehicle')
{
$vehicle = getVehicleValuation();
if(($serials = $vehicle['SerialEquipment']) === null){
// doesn't contain SerialEquipment
break;
}
foreach($serials as $serial){
print "Code =>" . $serial->Code . "<br>";
print "Desc Short =>" . $serial->Desc_Short . "<br>";
//...
foreach($serial->Esaco as $esaco){
print "EsacoMainGroupCode =>" . $esaco->EsacoMainGroupCode. "<br>";
print "EsacoMainGroupDesc =>" . $esaco->EsacoMainGroupDesc. "<br>";
//...
}
}
}
And for the VehicleFuel:
if($parameter['aktion'] == 'getVehicle')
{
$vehicle = getVehicleValuation();
$Serial=$vehicle['SerialEquipment'];
$VehicleFuel=$vehicle['VehicleFuel'];
$fuelType = $VehicleFuel->Fuel_Type;
// if there is only going to be one VehicleFuel object Vehicle, then just do..
echo "Fuel Type =>". fuelType->Fuel_Type . "<br>";
echo "Fuel Type Code =>". $fuelType->Fuel_Type_Code . "<br>";
// if there will be more than one, you will want to use a loop...
foreach($fuelType as $obj)
{
echo "Fuel Type=>". $obj->Fuel_Type . "<br>";
echo "Fuel Type Code=>". $obj->Fuel_Type_Code . "<br>";
echo "ECE_Unit=>". $obj->ECE_Unit . "<br>";
echo "ECE_In=>". $obj->ECE_In . "<br>";
echo "ECE_Out=>". $obj->ECE_Out . "<br>";
echo "ECE_All=>". $obj->ECE_All . "<br>";
echo "ECE_CO2=>". $obj->ECE_CO2 . "<br>";
}
}
The key Esaco is an object not an array. You should change your second foreach.
foreach($Serial as $key => $obj) {
echo "Serial Equipment=>" . $key . "<br>";
echo "Code=>". $obj->Code . "<br>";
echo "Desc Short=>". $obj->Desc_Short . "<br>";
echo "Desc Long=>". $obj->Desc_Long . "<br>";
foreach($obj->Esaco as $key2 => $obj2) {
echo $obj2;
//...
}
}

php json not showing Wunderground station list

I'm trying to show a list of all nearby weather stations.
I have the code:
$json_string = file_get_contents("http://api.wunderground.com/api/8b19ccf6a06c0826/geolookup/conditions/q/Netherlands/Rotterdam.json");
$parsed_json = json_decode($json_string);
$stations = $parsed_json->{'location'}->{'nearby_weather_stations'}->{'pws'}->{'station'};
$count = count($stations);
for($i = 0; $i < $count; $i++)
{
$station = $stations[$i];
if (count($station) > 1)
{
echo "City: " . $station->{'city'} . "\n";
echo "State: " . $station->{'state'} . "\n";
echo "Latitude: " . $station->{'lat'} . "\n";
echo "Longitude: " . $station->{'lon'} . "\n";
}
}
But currently it's not showing anything, i have searched for examples but i couldn't find any solution fot this problem.
Alternatively, you could use a simple foreach to iterate those values. Consider this example:
$json_string = file_get_contents("http://api.wunderground.com/api/8b19ccf6a06c0826/geolookup/conditions/q/Netherlands/Rotterdam.json");
$parsed_json = json_decode($json_string, true); // <-- second parameter to TRUE to use it as an array
$desired_values = $parsed_json['location']['nearby_weather_stations']['pws']['station'];
foreach($desired_values as $key => $value) {
echo "<hr/>";
echo "City: " . $value['city'] . "<br/>";
echo "State: " . $value['state'] . "<br/>";
echo "Latitude: " . $value['lat'] . "<br/>";
echo "Longitude: " . $value['lon'] . "<br/>";
echo "<hr/>";
}
Sample Fiddle

Using arrays in PHP

I am working on my first program written in PHP. This is a basic question. I am trying to print a string stored in an array. I have two arrays. One array, $content, stores a number at $content[$i][15] (i am using arrays in arrays, and looping through it with a for loop). Lets say this number is 3. I now want to access a string in another array, called $type. This string is at position $type[3]. Logically, I think, $type[3] should print the same thing as $type[$content[$i][15]]. But, when I call $type[$content[$i][15]], it doesn't print anything, but when i print $type[3] it works fine. Is this type of call not allowed in PHP?
$type = array();
$typetemp = readfile("type.csv");
foreach ($typetemp as $sa){
$type[$sa[0]] = $sa[1];
}
$content = readfile("content.csv");
for($i=0; $i<sizeof($content); $i++){
if($content[$i][15] == 3){
if($content[$i][4] == 1){
$temp = $content[$i][15];
echo "id is " . $content[$i][0] . "title is " . $content[$i][1] . "introtext is " . $content[$i][2] . "restoftext is " . $content[$i][3] . "visible is " . $content[$i][4] . "category is " . $content[$i][5] . "creation_date is " . $content[$i][6] . "author is " . $content[$i][7] . "img is " . $content[$i][8] . "ordering is " . $content[$i][9] . "rank is " . $content[$i][10] . "vid is " . $content[$i][11] . "start_date is " . $content[$i][12] . "stop_date is " . $content[$i][13] . "event_date is " . $content[$i][14] . "type is " . $content[$i][15] . "thumb is " . $content[$i][16] . "type name is " . $type[$temp] . "<br/>";
}
}
}
function readfile($filename) {
$line_of_text = array();
$file_handle = fopen($filename, "r");
while (!feof($file_handle) ) {
array_push($line_of_text, fgetcsv($file_handle, 1024));
}
fclose($file_handle);
return $line_of_text;
}
You are missing a $ sign before content:
$type[$content[$i][15]]
This accesses the value in $type with index $content[$i][15]

PHP function, returning (in Windows) Rx and Tx for each adapter?

This is supposed to return raw values for Rx and Tx for each adapter (output is in pairs) ONLY of the adapter has transferred more than zero data.
<?php
//windows network usage testing
function win_netinfo(){
ob_start();
$wmi = new COM("Winmgmts://");
$nets = $wmi->execquery("SELECT * FROM Win32_PerfRawData_Tcpip_NetworkInterface WHERE BytesSentPersec > 1");
foreach ($nets as $net)
{
$net_txbytes = $net->BytesSentPersec;
$net_rxbytes = $net->BytesReceivedPersec;
if ($net_txbytes < 0) {
$net_txbytes = $net->BytesTotalPersec - $net->BytesReceivedPersec;
}
if ($net_rxbytes < 0) {
$net_rxbytes = $net->BytesTotalPersec - $net->BytesSentPersec;
}
return $net_txbytes . "</br>"; //When it RETURNS it only shows the FIRST value... :/ WHAT DO?
}
}
echo win_netinfo();
?>
Output should be like this:
21936313136
12345163517
13647613
87653467
546254
246247
87653642
24583462
(Every other line is Rx or Tx, for each adapter).
Current code that works:
<?php
# Peport All Errors
error_reporting(E_ALL);
# Create Object
$wmi = new COM("Winmgmts://");
# Get net info
$oss = $wmi->execquery("SELECT * FROM Win32_PerfRawData_Tcpip_NetworkInterface");
# Show net info
foreach($oss as $os)
{
echo "BytesReceivedPerSec: " . $os->BytesReceivedPerSec . "<br />";
echo "BytesSentPerSec: " . $os->BytesSentPerSec . "<br />";
echo "BytesTotalPerSec: " . $os->BytesTotalPerSec . "<br />";
echo "Caption: " . $os->Caption . "<br />";
echo "CurrentBandwidth: " . $os->CurrentBandwidth . "<br />";
echo "Description: " . $os->Description . "<br />";
echo "Frequency_Object: " . $os->Frequency_Object . " kb<br />";
echo "Frequency_PerfTime: " . $os->Frequency_PerfTime . "<br />";
echo "Frequency_Sys100NS: " . $os->Frequency_Sys100NS . "<br />";
echo "Name: " . $os->Name . "<br />";
echo "OutputQueueLength: " . $os->OutputQueueLength . "<br />";
echo "PacketsOutboundDiscarded: " . $os->PacketsOutboundDiscarded . "<br />";
echo "PacketsOutboundErrors: " . $os->PacketsOutboundErrors . "<br />";
echo "PacketsReceivedNonUnicastPerSec: " . $os->PacketsReceivedNonUnicastPerSec . "<br />";
echo "PacketsReceivedPerSec: " . $os->PacketsReceivedPerSec . "<br />";
echo "PacketsReceivedUnicastPerSec: " . $os->PacketsReceivedUnicastPerSec . "<br />";
echo "PacketsReceivedUnknown: " . $os->PacketsReceivedUnknown . "<br />";
echo "PacketsSentNonUnicastPerSec: " . $os->PacketsSentNonUnicastPerSec . "<br />";
echo "PacketsSentPerSec: " . $os->PacketsSentPerSec . "<br />";
echo "PacketsSentUnicastPerSec: " . $os->PacketsSentUnicastPerSec . "<br />";
echo "Timestamp_Object: " . $os->Timestamp_Object . "<br />";
echo "Timestamp_PerfTime: " . $os->Timestamp_PerfTime . "<br />";
echo "Timestamp_Sys100NS: " . $os->Timestamp_Sys100NS . "<br />";
echo "<br /><br /><br />";
}
?>
Your returning after the first iteration hence only 1 result, below is how i would do it by creating an array and returning that instead:
<?php
//windows network usage testing
function win_netinfo(){
$wmi = new COM("Winmgmts://");
$nets = $wmi->execquery("SELECT * FROM Win32_PerfRawData_Tcpip_NetworkInterface WHERE BytesSentPersec > 1");
$return=array();
$i=0;
foreach ($nets as $net){
$return[$i]['name']=$net->Name;
if ($net->BytesSentPersec < 0) {
$return[$i]['net_txbytes'] = $net->BytesTotalPersec - $net->BytesReceivedPersec;
}else{
$return[$i]['net_txbytes'] = $net->BytesSentPersec;
}
if ($net->BytesReceivedPersec < 0) {
$return[$i]['net_rxbytes'] = $net->BytesTotalPersec - $net->BytesSentPersec;
}else{
$return[$i]['net_rxbytes'] = $net->BytesReceivedPersec;
}
$i++;
}
return $return;
}
$adapters=win_netinfo();
/*Array
Array
(
[0] => Array
(
[name] => VirtualBox Host-Only Ethernet Adapter
[net_txbytes] => 5095956
[net_rxbytes] => 0
)
[1] => Array
(
[name] => Belkin 54g Wireless USB Network Adapter
[net_txbytes] => 532337967
[net_rxbytes] => 5252455518
)
)
*/
?>
And to output the array, something like this:
<?php
foreach($adapters as $adapter){
echo '<p>'.$adapter['name'].' - Sent: '.$adapter['net_txbytes'].' bytes - Received: '.$adapter['net_rxbytes'].' bytes</p>';
}
?>

Categories