如何基于数量扩展数组

时间:2019-01-15 07:47:25

标签: php

我有一个存储数量的数组。我想按如下所述将其转换为单个数组

我尝试过的事情

function expandArray($TICKETTYPE_TEMPARRAY, $readQuantity){
    for($i=1; $i<=$readQuantity; $i++){
        $TICKETTYPE[] = $TICKETTYPE_TEMPARRAY;
    }
}


foreach($TICKETTYPE_TEMPARRAY as $key => $value){
  $readQuantity = $value["QUANTITY"];
  expandArray($TICKETTYPE_TEMPARRAY, $readQuantity);
}

我的阵列

$myarray = array(
  "TICKETPRICE" => "6.0000",
  "QUANTITY" => "2",
  "COUNTRYID" => "15"
)

预期输出:

[{TICKETPRICE:6.000, QUANTITY:2, COUNTRYID=15},
{TICKETPRICE:6.000, QUANTITY:2, COUNTRYID=15}]

2 个答案:

答案 0 :(得分:3)

我认为您想要这样的东西:

$myarray = array(array(
  "TICKETPRICE" => "6.0000",
  "QUANTITY" => "2",
  "COUNTRYID" => "15"
),
array(
  "TICKETPRICE" => "4.0000",
  "QUANTITY" => "3",
  "COUNTRYID" => "9"
));

$output = array();
foreach ($myarray as $array) {
    $output[] = array_fill(0, $array['QUANTITY'], $array);
}
echo json_encode($output);

输出:

[[{"TICKETPRICE":"6.0000","QUANTITY":"2","COUNTRYID":"15"},
  {"TICKETPRICE":"6.0000","QUANTITY":"2","COUNTRYID":"15"}
 ],
 [{"TICKETPRICE":"4.0000","QUANTITY":"3","COUNTRYID":"9"},
  {"TICKETPRICE":"4.0000","QUANTITY":"3","COUNTRYID":"9"},
  {"TICKETPRICE":"4.0000","QUANTITY":"3","COUNTRYID":"9"}
]]

或者如果您想要一个完全平坦的阵列:

$output = array();
foreach ($myarray as $array) {
    $output = array_merge($output, array_fill(0, $array['QUANTITY'], $array));
}
echo json_encode($output);

输出:

[{"TICKETPRICE":"6.0000","QUANTITY":"2","COUNTRYID":"15"},
 {"TICKETPRICE":"6.0000","QUANTITY":"2","COUNTRYID":"15"}
 {"TICKETPRICE":"4.0000","QUANTITY":"3","COUNTRYID":"9"},
 {"TICKETPRICE":"4.0000","QUANTITY":"3","COUNTRYID":"9"},
 {"TICKETPRICE":"4.0000","QUANTITY":"3","COUNTRYID":"9"}
]

Demo on 3v4l.org

答案 1 :(得分:2)

仅array_fill和json_encode可能会对您有所帮助。

<?php
$myarray = array(
    "TICKETPRICE" => "6.0000",
    "QUANTITY" => "2",
    "COUNTRYID" => "15"
);

$myarray = json_encode(array_fill(0, $myarray['QUANTITY'], $myarray));

print '<pre>';
print_r($myarray);
?>