"1138" "product_image" => "/resources/medias/shop/pro-6ren">
gpt4 book ai didi

php - 基于另一个数组保留二维数组的每一行中的元素

转载 作者:可可西里 更新时间:2023-11-01 00:08:01 25 4
gpt4 key购买 nike

我有这个数组:

0 => array:3 [
"product_id" => "1138"
"product_image" => "/resources/medias/shop/products/shop-6500720--1.png"
"product_sku" => "6500722"
]
1 => array:3 [
"product_id" => "1144"
"product_image" => "/resources/medias/shop/products/shop-6501041--1.png"
"product_sku" => "6501046"
]
2 => array:3 [
"product_id" => "113"
"product_image" => "/resources/medias/shop/products/shop-6294909--1.png"
"product_sku" => "6294915"
]

我正在寻找的是一种获取仅包含所需列的多数组的方法(array_column 不是一个选项,因为它只给我一个列)。

我做了什么

function colsFromArray($array, $keys)
{
return array_map(function ($el) use ($keys) {
return array_map(function ($c) use ($el) {
return $el[$c];
}, $keys);
}, $array);
}

$array = array(
[
"product_id" => "1138",
"product_image" => "/resources/medias/shop/products/shop-6500720--1.png",
"product_sku" => "6500722"
],
[
"product_id" => "1144",
"product_image" => "/resources/medias/shop/products/shop-6501041--1.png",
"product_sku" => "6501046"
],
[
"product_id" => "113",
"product_image" => "/resources/medias/shop/products/shop-6294909--1.png",
"product_sku" => "6294915"
]
);
colsFromArray($array, array("product_id", "product_sku"));

//0 => array:3 [
// "product_id" => "1138"
// "product_sku" => "6500722"
// ]
//1 => array:3 [
// "product_id" => "1144"
// "product_sku" => "6501046"
// ]
//2 => array:3 [
// "product_id" => "113"
// "product_sku" => "6294915"
//]

问题是它看起来太滞后,因为它对此进行了两次迭代。如果没有此解决方法,是否有任何方法可以获取多个列?

我用的是PHP5.6

最佳答案

如果您需要数组中的两列,其中一列是 SKU(通常是唯一的),那么您可以将 array_column 与第三个参数一起使用。

$new = array_column($arr, "product_id", "product_sku");

这将返回一个平面数组,其中 SKU 作为键,ID 作为值,使数组也易于使用。

输出:

array(3) {
[6500722]=>
string(4) "1138"
[6501046]=>
string(4) "1144"
[6294915]=>
string(3) "113"
}

https://3v4l.org/UDGiO

关于php - 基于另一个数组保留二维数组的每一行中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52706383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com