数组的所有键和值如何在自己的数组中生成?

时间:2014-04-13 00:26:19

标签: php arrays multidimensional-array

假设我的数组看起来像这样:

Array
(
    [0] = Charcoal,Natural Gas,Combo
    [1] = Charcoal,Propane,Combo
    [2] = Charcoal,Propane,Natural Gas,Combo
    [3] = Natural Gas
)

我该怎么做才能让它看起来像这样:

Array
(
    [0] = Charcoal,Natural Gas,Combo
)
Array
(
    [0] = Charcoal,Propane,Combo
)
Array
(
    [0] = Charcoal,Propane,Natural Gas,Combo
)
Array
(
    [0] = Natural Gas
)

3 个答案:

答案 0 :(得分:0)

乍一看我会建议:

$array = Array
(
    [0] = Charcoal,Natural Gas,Combo
    [1] = Charcoal,Propane,Combo
    [2] = Charcoal,Propane,Natural Gas,Combo
    [3] = Natural Gas
);
$array2 = array();
foreach ($array as $item) {
    $array2[][] = $item;
}

第二个想法,而不是显示你想要它的样子的新数组,你向我展示了多个数组。这意味着这样的实现:

foreach ($array as $item) {
    print_r($item);
}

答案 1 :(得分:0)

   ## hope this helps ##

  <?php
$array = Array('Charcoal, Natural 
Gas,Combo','Charcoal,Propane,Combo','Charcoal,Propane,Natural Gas,Combo', 'Natural 
Gas');

$d1 = array_slice($array, 0, 1);
$d2 = array_slice($array, 1, 1);
$d3= array_slice($array, 2, 1);
$d4 = array_slice($array, 3, 1);

echo "<pre>";
print_r($d1);
print_r($d2);
print_r($d3);
print_r($d4);
echo "</pre>";


?>

答案 2 :(得分:0)

您可以使用array_chunk()功能。

$array = array('Charcoal, Natural gas, Combo' ,'Charcoal,Propane,Combo', 'Charcoal,Propane,Natural Gas, Combo', 'Natural Gas' );

$arr = array_chunk($array,1);

请参阅demo