开发者

using trim with arrays in php

开发者 https://www.devze.com 2023-02-05 10:55 出处:网络
I have following array Array ( [0] =>  [1] => Commodities [2] => Crude Oil [3] => 91.46 [4] => + 0.48% [5] => Natural Gas [6] => 4.54 [7] => + 0.38% [8] => Gasoline

I have following array

Array ( [0] =>  [1] => Commodities [2] => Crude Oil [3] => 91.46 [4] => + 0.48% [5] => Natural Gas [6] => 4.54 [7] => + 0.38% [8] => Gasoline [9] => 2.49 [10] => + 0.49% [11] => Heating Oil [12] => 2.65 [13] => + 0.84% [14] => Gold [15] => 1368.07 [16] => + 0.40% [17] => Silver [18] => 28.78 [19] => + 1.62% [20] => Copper [21] => 4.41 [22] => + 0.14% [23] => Quotes delayed 15 min. [24] => » Add to your site )

i want an array like

Array([0]=>Array
(name => Crude oil
price => 91.46
precent => +0.48)
[1]=>Array
(name => Natural Gas
...
..
and so on upto Copper
)

i tried using

for ($i = 2; $i <6 ; $i = $i +3) {
   $commoditiesdatagot[] = array (
   trim($arraymain[$i]),
   trim($arraymain[$i +1]),
   trim($arraymain[$i +2])
   );
  }

but i keep getting following error -

PHP Warning:  Module 'mcrypt' already loaded in Unknown on line 0
PHP Notice:  Undefined offset:  25 in /var/www/html/iphorex/live/commodities.php on line 51

Notice: Undefined offset:  25 in /var/www/html/iphorex/live/commodities.php on line 51
PHP Notice:  Undefined offset:  26 in /var/www/html/iphorex/live/co开发者_C百科mmodities.php on line 49

Notice: Undefined offset:  26 in /var/www/html/iphorex/live/commodities.php on line 49
PHP Notice:  Undefined offset:  27 in /var/www/html/iphorex/live/commodities.php on line 50

where line 51 is trim($arraymain[$i +2]).

Any help ..........


You can use array_walk() to do this with a callback function:

// Define callback function, note &$item is passed by reference
function trim_r(&$item, $key)
{
    // If the item is an array, recursively use array_walk 
    if(is_array($item))
        array_walk($item, 'trim_r');
    // Trim the item
    else if(is_string($item))
        $item = trim($item);
}

// This is an example array
$yourArray = array(" Jake ", " John ", array( " Helen "));

// Show the array without being trimmed
var_dump($yourArray);

// Trim the array
array_walk($yourArray, 'trim_r');

// Display the trimmed array
var_dump($yourArray);


The problem is not with trim(). In your for() cycle, you are sending your $i variable to 25, 26, 27 ([$i], [$i+1], [$i+2]) while your $arraymain has 24 elements in it.

$arraymain = array_slice($arraymain,2,-2);
for ($i = 0; $i < count($arraymain); $i += 3) {
   $commoditiesdatagot[] = array (
   trim($arraymain[$i]),
   trim($arraymain[$i+1]),
   trim($arraymain[$i+2])
   );
  }

print_r($arraymain);


you have to check if your loop uses the correct interval. the error message tells you, that you try to access a variable in your array on position: 25 and 26, but your array only has 25 items indexed by 0 to 24. so array[25] is not available.

your loop could also look like this i guess:

$i = 2;
while($i < count($arraymain)){
   $row = array();
   if(isset($arraymain[$i+2]){
      $row[] = $arraymain[$i]; $i++;
      $row[] = $arraymain[$i]; $i++;
      $row[] = $arraymain[$i]; $i++;

      $commoditiesdatagot[] = $row;
    } else error_log("index out of bounce ".$i+2);
}


Here is an all-in-one:

array_map(                                      // apply
    function($chunk) {                          // this callback that
        return array_combine(                   // makes a new array
            array('name', 'price', 'percent'),  // with these keys
            array_map('trim', $chunk)           // and those trimmed values
        );
    },                                          
    array_chunk(                                // from the chunks of
        array_slice($data, 2, -2),              // this $data array subset
        3                                       // having three chunks each
     )
 );

Note that this requires the input data to have 3 elements each per Commodity. Your input array is missing a price for Gasoline, so any solutions presented so far will choke on that when creating the commodity subsets.

You could also move the trimming into the lower part before you are chunking the array. This would invoke the call just once instead of multiple times on the individual chunks. Not sure if it makes a huge difference though.

See live demo

0

精彩评论

暂无评论...
验证码 换一张
取 消