我在处理数组PHP中遇到麻烦,我有一个数组:
[0] {
'email' => 'test@gmail.com',
'meta' => {
'product' => {
'id' => '1',
'content' => 'This is content'
}
}
}
[1] {
'email' => 'test2@gmail.com',
'meta' => {
'product' => {
'id' => '2',
'content' => 'This is content'
}
}
}
[2] {
'email' => 'test2@gmail.com',
'meta' => {
'product' => {
'id' => '3',
'content' => 'This is content'
}
}
}
我需要按值'email'
合并此数组,如下所示:
[0] {
'email' => 'test@gmail.com',
'meta' => {
'product' => {
'id' => '1',
'content' => 'This is content'
}
}
}
[1] {
'email' => 'test2@gmail.com',
'meta' => {
'product' => [0] {
'id' => '2',
'content' => 'This is content'
}
[1] {
'id' => '3',
'content' => 'This is content'
}
}
}
有人能帮助我吗?
答案 0 :(得分:2)
$sorted_array = [];
$emails = [];
$i = 0;
foreach ($arr as $array) {
if(!empty($array['email']) && !empty($array['meta']['product'])){
if( in_array($array['email'], $emails)){
$i--;
} else {
$emails[] = $array['email'];
}
$sorted_array[$i]['email'] = $array['email'];
$sorted_array[$i]['meta']['product'][] = $array['meta']['product'];
$i++;
}
}
echo "<pre>";
print_r($sorted_array);
希望这会对你有所帮助
答案 1 :(得分:0)
Php具有许多排序数组的功能。您可以查阅文档,为您的案例http://php.net/manual/en/array.sorting.php选择更好的算法。你可以将结果数组与array_merge函数合并,就像它:
array_merge($ A1,$ A2)
我在这里为您的代码创建了一个示例:
答案 2 :(得分:0)
你可以使用像数组的密钥这样的电子邮件来结束,使用array_combine从0到N的数字有一个indeces ......
<?php
$oldArray = array(
array(
'email' => 'test@gmail.com',
'meta' => array(
'product' => array(
'id' => '1',
'content' => 'This is content'
)
)
), array(
'email' => 'test2@gmail.com',
'meta' => array(
'product' => array(
'id' => '2',
'content' => 'This is content'
)
)
), array(
'email' => 'test2@gmail.com',
'meta' => array(
'product' => array(
'id' => '3',
'content' => 'This is content'
)
)
)
);
$newArray = array();
foreach($oldArray as $element){
if(isset($newArray[$element['email']])) {
if(!isset($newArray[$element['email']]['meta']['product'][0]))
$newArray[$element['email']]['meta']['product'] = array($newArray[$element['email']]['meta']['product']);
$newArray[$element['email']]['meta']['product'][] = $element['meta']['product'];
} else {
$newArray[$element['email']] = $element;
}
}
//For index since 0 to n
print_r(array_combine(range(0,count($newArray)-1), $newArray));
答案 3 :(得分:-1)
您可以使用已排序的信息构建新数组。
应该使用类似的东西,但没有经过测试:
$sorted_array = [];
$i = 0;
foreach ($unsorted_array as $array) {
if(!empty($array['email']) && !empty($array['meta']['product'])){
$sorted_array[$i]['email'] = $array['email'];
$sorted_array[$i]['meta']['product'][] = $array['meta']['product'];
$i++;
}
}
print_r($sorted_array);