简体   繁体   中英

php looping through 2D array

I access the following values like this.

$result->{'HistoricalPricesResult'}->HistoricalPricesResult[0]->Price
$result->{'HistoricalPricesResult'}->HistoricalPricesResult[0]->Low
//next row
$result->{'HistoricalPricesResult'}->HistoricalPricesResult[1]->Price
$result->{'HistoricalPricesResult'}->HistoricalPricesResult[1]->Low

However I need to consolidate this to

$values[0][price]
$values[0][low]
$values[1][price]
$values[1][low]

2 other strange things. The values are strings and I need them to be decimals(2 decimal points) and also the min and the max for price and low accross all the rows

Well the obvious way to build an array of values would be:

$values = array();
for($i = 0; $i < some_maximum_value; $i++) {
   $values[$i] = array(
      'price' => $result->{'HistoricalPricesResult'}->HistoricalPricesResult[$i]->Price,
      'low' => $result->{'HistoricalPricesResult'}->HistoricalPricesResult[$i]->Low,
   );
}

TADAAAAAA!!!!

$values = array();
foreach($result->{'HistoricalPricesResult'}->HistoricalPricesResult as $key => $obj){
    $values[$key]['price'] = $obj->Price;
    $values[$key]['low'] = $obj->low;
}
$myVals = array();
foreach ($result->{'HistoricalPricesResult'}->HistoricalPricesResult as $key => $v)
{
   $myVals[$key]['price'] = 1.0 * $c->Price;  //hoping string has 2 after the decimal
   $myVals[$key]['low'] = 1.0 * $c->Low
}

Try to figure out max/min yourself

Check out foreach loops and string/float conversion

http://us2.php.net/manual/en/control-structures.foreach.php
http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM