我有一个数组,其中包含重复的手机号码和相应的值,我想将这些手机号码和相应的对象合并
这是我完成的实际语法
foreach($char2['flowers_details'] as $flowers){
foreach($array as $flowersd){
if (in_array($flowers['flower_id'], $flowersd['flower_id'])){
$details[] = array('mobile'=>$flowersd['mobile'],'flower_name'=>$flowers['flower_name'],'flower_price'=>$flowers['flower_price']);
}
}
}
echo json_encode($details);
这是回应
[
{
"mobile": "7799124599",
"flower_name": "Merabel ",
"flower_price": "20"
},
{
"mobile": "8008118599",
"flower_name": "Merabel ",
"flower_price": "20"
},
{
"mobile": "8008118599",
"flower_name": "San maggi ",
"flower_price": "10"
},
{
"mobile": "7799124599",
"flower_name": "Mango yellow ",
"flower_price": "50"
}]
这不是完美的伴侣 而且即使我尝试了这种语法,我也无法获得准确的格式化数组
foreach($char2['flowers_details'] as $flowers){
foreach($array as $flowersd){
$mobile = array('mobile'=>$flowersd['mobile']);
if (in_array($flowers['flower_id'], $flowersd['flower_id'])){
$detail[] = array('flower_name'=>$flowers['flower_name'],'flower_price'=>$flowers['flower_price']);
}
$details = array_merge($mobile,$detail);
}
}
echo json_encode($detail);
所以,我应该以哪种方式编写语法以获得完美的数组格式 显示一个数字和其他后续值
我也想展示的实际伙伴是
[
[
{
"mobile": "7799124599"
},
{
"flower_name": "Merabel ",
"flower_price": "20"
},
{
"flower_name": "Mango yellow ",
"flower_price": "50"
}
],
[
{
"mobile": "8008118599"
},
{
"flower_name": "Merabel ",
"flower_price": "20"
},
{
"flower_name": "San maggi ",
"flower_price": "10"
}
]
]
谢谢
答案 0 :(得分:2)
您必须像下面那样更改分配代码:-
$details[$flowersd['mobile']][] = array('mobile'=>$flowersd['mobile'],'flower_name'=>$flowers['flower_name'],'flower_price'=>$flowers['flower_price']);
以上代码将创建手机号码作为键,因此,如果您不想这样做,请在json_encode()
之前执行此操作:-
$details = array_values($details); //will re-indexed array keys to 0,1,2,....