1

我的产品阵列 -

Array
(
    [0] => Product1
    [1] => 
    [2] => 
    [3] => 
    [4] => Product2
    [5] => 
    [6] => 
    [7] => Product3
    [8] => Product4
    [9] => Product5
)

Desired output-

Array
(
    [0] => Product1
    [1] => Product1
    [2] => Product1
    [3] => Product1
    [4] => Product2
    [5] => Product2
    [6] => Product2
    [7] => Product3
    [8] => Product4
    [9] => Product5
)

我的代码尝试 -

$i = 0;
$newone = array();
for( $i; $i < count($newarr); $i++ )
{
    if( $newarr[$i] != '' )
    {
        $newone[$i] = $newarr[$i];
    }
    else
    {
        $newone[$i] = $newarr[$i-1];
    }
}

echo "<pre>";print_r($newone);

此代码的输出 -

Array
(
    [0] => Product1
    [1] => Product1
    [2] => 
    [3] => 
    [4] => Product2
    [5] => Product2
    [6] => 
    [7] => Product3
    [8] => Product4
    [9] => Product5
)

让我知道如何操纵我的代码来实现这种数组。

4

4 回答 4

2

我猜你在你的代码中犯了一个小错误。你正在做的是,在这里放一个空的东西($newone[$i] = $newarr[$i-1];)。它应该是$newone[$i-1]。看看这里

<?php

$newarr= Array( 'Product1', '', '', 'Product2', '', '', 'Product3', 'Product4', 'Product5');

print_r($newarr);
$i = 0;

$newone = array();
for( $i; $i < count($newarr); $i++ )
{
   if( $newarr[$i] != '' )
   {
     $newone[$i] = $newarr[$i];
   }
   else
   {
      $newone[$i] = $newone[$i-1];
   }
}

echo "<pre>";print_r($newone);



?>
于 2013-03-15T06:29:33.517 回答
1
$newArray = array();

foreach($products as $product)
{
    if($product != '')
    {
        $currentProduct = $product;
    }

    $newArray[] = $currentProduct;
}

print_r($newArray);

请参阅键盘

于 2013-03-15T06:18:49.190 回答
1

这是我的代码试试看

<?php
$newarr = array('Product1','','','Product2','','','Product3','Product4','Product5');
$newone = array();
$tempValue = '';
foreach($newarr as $key=>$value)
{
   if(($tempValue != $value) && ($value !== ''))
   {
      $tempValue = $value;
   }

   if( $value != '' )
   {
      $newone[$key] = $newarr[$key];
   }
   else
  {
      $newone[$key] = $tempValue;
   }
}

echo "<pre>";print_r($newone);
?>
于 2013-03-15T06:28:26.523 回答
0

检查此代码:这不使用任何循环:

$arr  = array('Product1','','','','','Product2','','','Product3','Product4','Product5');

$i    = 0;
$assoc_arr = array_reduce($arr, function ($result, $item) use(&$i) {
    $result[$i] = ($item == '') ? $result[$i-1] : $item;
    $i++;
    return $result;
}, array());


echo "<pre>";
print_r($assoc_arr);
于 2013-03-15T08:31:23.743 回答