【发布时间】:2019-10-01 06:43:59
【问题描述】:
我需要形成最终的数组,它没有显示我的期望,这是我使用的代码。
我需要以预期的格式打印最终的数组,我已经在下面的部分中附加了我正在寻找的输出,
<?php
$order_id = 12345;
$array1 = array(
"firstName" => "Test Fname",
"lastName" => "Test Lname",
"address1" => "Test Address",
"city" => "Test City",
"country" => "IND",
"email" => "test@blank.in"
);
$array2 = array(
"firstName" => "Test Fname",
"lastName" => "Test Lname",
"address1" => "Test Address",
"city" => "Test City",
"country" => "IND",
"email" => "test@blank.in"
);
$result = array("user_id" =>"9999","item_id" =>"cloth","price" =>"500","qty" =>"100");
$itemDetails = array();
foreach($result as $res){
$itemDetails[] =
array(
"User" => array(
"uservalue" => $res['user_id'],
"imageId" => $res['item_id']
),
"price" => $res['price'],
"qty" => $res['qty']
);
}
$final_array = array(
"id" => $order_id,
"billing" => $array1,
"shipping" => $array2,
"item" => $itemDetails
);
echo '<pre>';
print_r($final_array);die;
?>
当前代码的输出
Array
(
[id] => 12345
[billing] => Array
(
[firstName] => Test Fname
[lastName] => Test Lname
[address1] => Test Address
[city] => Test City
[country] => IND
[email] => test@blank.in
)
[shipping] => Array
(
[firstName] => Test Fname
[lastName] => Test Lname
[address1] => Test Address
[city] => Test City
[country] => IND
[email] => test@blank.in
)
[item] => Array
(
[0] => Array
(
[User] => Array
(
[uservalue] => 9999
[imageId] => cloth
)
[price] => 500
[qty] => 100
)
[1] => Array
(
[User] => Array
(
[uservalue] => 9999
[imageId] => cloth
)
[price] => 500
[qty] => 100
)
[2] => Array
(
[User] => Array
(
[uservalue] => 9999
[imageId] => cloth
)
[price] => 500
[qty] => 100
)
)
)
预期结果应如下所示
array
(
"id" => 12345
"billing" => array
(
[firstName] => Test Fname,
[lastName] => Test Lname,
[address1] => Test Address,
[city] => Test City,
[country] => IND,
[email] => test@blank.in
)
"shipping" => array
(
[firstName] => Test Fname,
[lastName] => Test Lname,
[address1] => Test Address,
[city] => Test City,
[country] => IND,
[email] => test@blank.in
)
"item" => array
(
array
(
"User" => Array
(
"uservalue" => 9999,
"imageId" => cloth
)
[price] => 500,
[qty] => 100
)
)
)
我期待像上面这样的输出,我们能否以该格式显示最终数组,任何人都可以查看它并更新您的想法。谢谢!!
【问题讨论】:
-
您的输出现在看起来如何?
-
如果
result数组是多维数组或在没有foreach 循环的情况下将值分配给itemDetails,您可以获得上述结果 -
@PragneshChauhan,请发帖作为答案,如果结果数组有多个值,则用键显示
-
接下来可能值得一读面向对象的内容,其中很多内容可以通过对象、集合和 getter/setter 来处理。
-
怎么说它是一个重复的问题,要求不同。@mickmackusa
标签: php arrays associative-array