0

这是我的product阵列 -

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

这是category产品的阵列 -

Array
(
    [0] => Array
        (
            [0] => 'cat1'
            [1] => 'cat2'
            [2] => 'cat3'
            [3] => 'cat4'
            [4] => 'cat5'
            [5] => 'cat6'
            [6] => 'cat7'
            [7] => 
            [8] => 
            [9] => 
        )
)

需要这种格式的最终​​输出 -

Array
(
'Product1' => Array(
           [0] => 'cat1',
           [1] => 'cat2',
           [2] => 'cat1',
           [3] => 'cat4'
           ),
'Product2' => Array(
           [0] => 'cat5',
           [1] => 'cat6',
           [2] => 'cat7'
           ),
'Product3' => Array(
           [0] => 'No Cat'
           ),
'Product4' => Array(
           [0] => 'No Cat'
           ),
'Product5' => Array(
           [0] => 'No Cat',
           )
)

我试过了,但这没有形成正确的输出——

$newarr = array();
foreach( $productData[0] as $arr1 )
{

    if( $arr1 != '' )
    {
        foreach( $catData[0] as $catnames ){
        $newarr[$arr1] = array($compnames);
        }
    }

}
echo "<pre>";print_r($newarr);
4

2 回答 2

2

试试这个。。

$newarr = array();
foreach( $productData[0] as $key => $product )
{

    if( $product != '' )
    {
        $newarr[$product] = array();
        $currentProduct = $product;

    }

    if( isset($catData[0][$key]) && ($catData[0][$key] != '') )
    {
        $newarr[$currentProduct][] = $catData[0][$key];
    }
    else
    {
         $newarr[$currentProduct][] = 'No Cat';
    }

}
echo "<pre>";print_r($newarr);
于 2013-03-13T06:43:52.537 回答
1

如果 count($productData[0]) == count($catData[0]) 您可以使用 for 循环。如果 $productData[0][0] 总是包含产品名称,那么这应该可以工作。

<?php
// array to return
$a = array();
// loop thru array
for($i = 0; $i < count($productData[0]); $i++) {
  // if the product name exists its time to start a new array entry
  if($productData[0][$i] != '') {
    // get the product name as we need might need this for the next iteration
    $current = $productData[0][$i];
    // create the new array
    $a[$current] = array();

    if($catData[0][$i] != '') {
      // and save the category at this iteration into the new array
      $a[$current][] = $catData[0][$i];
    } else {
      $a[$current][] = 'No Cat';
    }
  } else {
    // product name was blank, and $current should be set, append the category.
    $a[$current][] = $catData[0][$i];
  }
}

echo "<pre>";
print_r($a);
echo "</pre>";
于 2013-03-13T06:41:50.533 回答