多维数组推入 PHP

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"
    ]
];

我有两个数组 UID 共同用于两个数组,现在我想从 $userProductsData 获取 UPID 并推入 $userData,我试过不能正常工作,请任何人更新我的代码请 ?>

试试这个。


$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);

你的 $userProductsData 是一个常规数组,它有索引 0、1、2 等...然后你试图通过字符串键 "5f10482574d83d4b726fe5" 从这个数组中获取一个项目。

$userProductsData 应该是这样的键数组:

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

然后你可以通过键"5f10482574d83d4b726fe5"从这个数组中得到一个项目。