PHP:映射数组结果


PHP: Mapping array results

我从数据库检索到的结果包含一个包含汽车($resultsCars)的数组。每辆车的品牌都有标识。var_dump数组的结果如下:

array(2) {
  [0]=>
  array(2) {
    ["brand"]=>
    string(36) "2cb4c4d6-b706-e411-8ed9-0050568c4808"
    ["color"]=>
    string(5) "black"
  }
    [1]=>
  array(2) {
    ["brand"]=>
    string(36) "2cb4c4d6-b706-e411-8ed9-0050568c4807"
    ["color"]=>
    string(5) "white"
  } 
}

我的目标是将id替换为品牌的实际名称。为了实现这一点,我将使用一个数组,它将每个id映射到相应的汽车名称。var_dump这个数组($arrData)的结果如下:

array(3) {
  [0]=>
  object(some'path'here)#697 (2) {
    ["id":"some'path'here":private]=>
    string(36) "2cb4c4d6-b706-e411-8ed9-0050568c4806"
    ["name":"some'path'here":private]=>
    string(4) "Audi"
  }
 [1]=>
  object(some'path'here)#697 (2) {
    ["id":"some'path'here":private]=>
    string(36) "2cb4c4d6-b706-e411-8ed9-0050568c4807"
    ["name":"some'path'here":private]=>
    string(8) "Mercedes"
  }
  [2]=>
  object(some'path'here)#697 (2) {
    ["id":"some'path'here":private]=>
    string(36) "2cb4c4d6-b706-e411-8ed9-0050568c4808"
    ["name":"some'path'here":private]=>
    string(3) "BMW"
  }
}

为了创建一个基于$resultsCars的新数组,并解决了品牌id,我尝试了以下代码:

 $resultsMapped = [];
 foreach ($resultsCars as $result) {
     $result['brand'] = array_search($result['brand'], $arrData);
     $resultsMapped[] = $result;
 }
然而,结果数组中的brand字段包含布尔值false。我做错了什么?

您正在使用array_search,它将返回匹配的数组元素的索引,而不是元素本身。更重要的是,brands数组包含私有变量的对象,因此要访问它们必须有getter函数,而不能作为数组访问它们。

例如,不能这样做:
$arrData[0]['id']

如果对象变量是公共的,或者你正在使用StdClass,你可以这样访问它们:

$arrData[0]->id

否则,你必须实现getter函数,然后你可以使用:

$arrData[0]->getId()

可以使用array_map函数,将元素从一个数组映射到另一个数组。使用array_map,可以使用回调函数将品牌映射到汽车。

例如,如果你有一个getter函数:

$arrData = [...] // Contains the brands array
$func = function($car) {
    foreach ($arrData as $brand) {
        if ($car['brand'] === $brand->getId()) {
            $car['brand'] = $brand; break;
        }
    }
    return $car;
};
array_map($func, $resultsCars);

之后,您的$resultsCars数组将有品牌对象,而不是品牌ID字符串。

改变第一行$ resultsmap = [];to $ resultsmap = array();div . .

首先将$resultsMapped=[]声明更改为$resultsMapped=array();,然后更改

foreach ($resultsCars as $result) {
     $result['brand'] = array_search($result['brand'], $arrData);
     $resultsMapped[] = $result;
 }

foreach ($resultsCars as $result) {
     $result['brand'] = array_search($result['id'], $arrData);
     $resultsMapped[] = $result;
 }

希望这能解决你的问题