数组映射关系一对多怎么解决 php,php – 如何将两个数组映射成一个?

合并后的两个数组,如array_merge($array1,$array2);它变成这样,

array(10) {

[0]=>

object(stdClass) (2) {

["id"]=>

string(1) "1"

["text"]=>

string(5) "one"

}

[1]=>

object(stdClass) (2) {

["id"]=>

string(1) "2"

["text"]=>

string(8) "two"

}

[2]=>

object(stdClass) (2) {

["id"]=>

string(1) "3"

["text"]=>

string(4) "three"

}

[3]=>

object(stdClass) (2) {

["id"]=>

string(1) "4"

["text"]=>

string(8) "four"

}

[4]=>

object(stdClass) (2) {

["id"]=>

string(1) "5"

["text"]=>

string(3) "five"

}

[5]=>

object(stdClass) (2) {

["id"]=>

string(1) "1"

["unit"]=>

string(1) "0"

}

[6]=>

object(stdClass) (2) {

["id"]=>

string(1) "2"

["unit"]=>

int(0)

}

[7]=>

object(stdClass) (2) {

["id"]=>

string(1) "3"

["unit"]=>

int(0)

}

[8]=>

object(stdClass) (2) {

["id"]=>

string(1) "4"

["unit"]=>

string(1) "0"

}

[9]=>

object(stdClass) (2) {

["id"]=>

string(1) "5"

["unit"]=>

int(1)

}

}

这意味着两个数组都是字面上合并的.但我想要的是因为两个数组都有一个名为id的共同属性,它具有相同的值,

它应该变成:

array(2) {

[0]=>

object(stdClass) (2) {

["id"]=>

string(1) "1"

["text"]=>

string(5) "one"

["unit"]=>

int(0)

}

[1]=>

object(stdClass) (2) {

["id"]=>

string(1) "2"

["text"]=>

string(8) "two"

["unit"]=>

int(2)

}

}

请注意,arra1具有id,text而array2具有id,unit

我确实在这里引用了第一个建议使用array_map的答案,但对我来说,我得到的错误是说参数1不是数组.

编辑:

试过这个(不起作用):

$array1 = array_walk($array1, function(&$value) { $value = (array) $value; })

$array2 = array_walk($array2, function(&$value) { $value = (array) $value; })

function modifyArray($a, $b)

{

if (!empty($a) && !empty($b)) {

return array_merge($a, $b);

} else if (!empty($a) && empty($b)) {

return $a;

} else if (empty($a) && !empty($b)) {

return $b;

}

}

$new = array_map("modifyArray", $array1, $array2);

var_dump($new);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值