将列从一个数组复制到PHP中的其他列

时间:2018-01-24 12:23:58

标签: php arrays

$list = [

    {
        "id":67,
        "text":"Brands1",
        "class_3_main":[
            {
                "originalId":12,
                "name":"USA",
                "Id":"1",
                "mainSupplierIds":"23, 24, 32, 21, 39, 84, 23"
            },
            {
                "tag_id":6825,
                "name":"UK",
                "Id":"2307",
                "mainSupplierIds":"47, 11"
            }
        ],
        "class_3_suppliers":[
            {
                "originalId":6927,
                "name":"USA Suppliers",
                "supplierIds":''
            },
            {
                "tag_id":6928,
                "name":"UK Suppliers",
                "supplierIds":
            }
        ],
    }
]

我希望数组mainSupplierIds中的列class_3_mainsupplierIds数组的class_3_suppliers相关联。

最后我希望输出为:

"class_3_suppliers":[
        {
            "originalId":6927,
            "name":"USA Suppliers",
            "supplierIds":'23, 24, 32, 21, 39, 84, 23'
        },
        {
            "tag_id":6928,
            "name":"UK Suppliers",
            "supplierIds":'47, 11'
        }
    ],

我使用以下代码来实现此目的:

$result = array_map(create_function('$arr', 'return $arr["mainSupplierIds"];'), $class_3_main);
$class_3_suppliers['supplierIds'] = $result;

但结果结合了supplierIds和返回的resukt

"class_3_suppliers":[
    {
        "originalId":6927,
        "name":"USA Suppliers",
        "supplierIds":[
            0: '23, 24, 32, 21, 39, 84, 23',
            1: '47,11'
        ]
    },
    {
        "tag_id":6928,
        "name":"UK Suppliers",
        "supplierIds":[
            0: '23, 24, 32, 21, 39, 84, 23',
            1: '47,11'
        ]
    } ],

1 个答案:

答案 0 :(得分:1)

如果这应该是具有这些值的PHP对象,并且它们将始终具有相同的名称,其中包含ID' s以及class_3_main和class_3_suppliers中的相同数量,那么这可以起作用。

$list = [
    "id"=>67,
    "text"=>"Brands1",
    "class_3_main"=>[[
            "originalId"=>12,
            "name"=>"USA",
            "Id"=>"1",
            "mainSupplierIds"=>"23, 24, 32, 21, 39, 84, 23"
        ],
        [
            "tag_id"=>6825,
            "name"=>"UK",
            "Id"=>"2307",
            "mainSupplierIds"=>"47, 11"
        ]
    ],
    "class_3_suppliers"=>[
        [
            "originalId"=>6927,
            "name"=>"USA Suppliers",
            "supplierIds"=>""
        ],
        [
            "tag_id"=>6928,
            "name"=>"UK Suppliers",
            "supplierIds"=>""
        ]
    ]
];

$class3Mains = $list["class_3_main"];
$class3Suppliers = $list["class_3_suppliers"];
$index = 0;

foreach($class3Mains as $class3Main) {
    $class3Suppliers[$index]["supplierIds"] = $class3Main["mainSupplierIds"];
    $index++;
}

var_dump($class3Suppliers);

从class_3_main和class_3_suppliers中取出数组并循环它们并将值从一个属性复制到另一个属性。 我添加的脚本可以在此处测试:http://www.writephponline.com/