在 php 中使用数组修剪

发布于 2024-10-12 16:56:22 字数 1572 浏览 7 评论 0原文

我有以下数组,

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 )

我想要一个像

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

我尝试使用的

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

数组,但我不断收到以下错误 -

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/commodities.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

其中第 51 行是 trim($arraymain[$i +2])

任何帮助.........

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/commodities.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 ..........

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

悸初 2024-10-19 16:56:22

您可以使用 array_walk() 通过回调函数来执行此操作:

// 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);

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);
海拔太高太耀眼 2024-10-19 16:56:22

问题不在于trim()。在 for() 循环中,您将 $i 变量发送到 25, 26, 27 ([$i], [$i+1], [$i+2]),而 $arraymain 中有 24 个元素。

$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);

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);

花想c 2024-10-19 16:56:22

您必须检查循环是否使用正确的间隔。错误消息告诉您,您尝试访问数组中位置为 25 和 26 的变量,但您的数组只有 25 个索引为 0 到 24 的项目。因此 array[25] 不可用。

我猜你的循环也可能是这样的:

$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);
}

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);
}
筱果果 2024-10-19 16:56:22

这是一个全合一的:

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
     )
 );

请注意,这要求输入数据每个商品有 3 个元素。您的输入数组缺少汽油价格,因此迄今为止提出的任何解决方案在创建商品子集时都会受到阻碍。

您还可以在对数组进行分块之前将修剪移到下部。这只会对各个块调用一次,而不是多次。但不确定它是否会产生巨大的差异。

观看现场演示

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文