简体   繁体   中英

multidimensional array push in PHP

    <?php
$userData = [
    [
        "UID" => "5f10482574d83d4b726fe5",
        "name" => "Yug Gill",
        "orgID" => "5f10481d74d83d4b726",
        "imageURL" => "female.png"
    ]
];

$userProductsData = [
    [
    "UPID" => "5f10482574d83d4b6fe007",
    "UID" => "5f10482574d83d4b726fe5",
    ]
];
$userDetailsResult = [];
foreach ($userData as $key => $value) {
    $userData[$key]["UPID"] = $userProductsData[$value["UID"]] ?? [];
}

Expected Output

$userData = [
    [
        "UID" => "5f10482574d83d4b726fe5",
        "name" => "Yug Gill",
        "orgID" => "5f10481d74d83d4b726",
        "imageURL" => "female.png",
        "UPID" => "5f10482574d83d4b6fe007"
    ]
];

i have two aray UID common for both array, now i want to take UPID from $userProductsData and push into $userData , i have tried not working properly, kindly anyone update my code please ?>

Try this one.


$userData = [
    [
        "UID" => "5f10482574d83d4b726fe5",
        "name" => "Yug Gill",
        "orgID" => "5f10481d74d83d4b726",
        "imageURL" => "female.png"
    ]
];

$userProductsData = [
    [
    "UPID" => "5f10482574d83d4b6fe007",
    "UID" => "5f10482574d83d4b726fe5",
    ]
];
$userDetailsResult = [];

foreach ($userProductsData as $key => $value) {
    $userData[$key]["UPID"] = $value['UPID'];
   
}

print_r($userData);

Your $userProductsData is a regular array, it has indexes 0, 1, 2 etc... Then you are trying to get an item from this array by string key "5f10482574d83d4b726fe5" .

$userProductsData should be a key array like that:

$userProductsData = [
    "5f10482574d83d4b726fe5" => [
        "UPID" => "5f10482574d83d4b6fe007",
        "UID" => "5f10482574d83d4b726fe5",
    ],
];

Then you can get an item from this array by key "5f10482574d83d4b726fe5" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM