PHP:数组按索引值隔离
PHP: Array Segregation By Index Value
我有一个这样的数组:
[
{
"id": "13216",
"image_type": "ThumbnailImage",
"is_primary": "1"
},
{
"id": "13217",
"image_type": "MediumImage",
"is_primary": "1"
},
{
"id": "13218",
"image_type": "LargeImage",
"is_primary": "1"
},
{
"id": "13219",
"image_type": "ThumbnailImage",
"is_primary": "0"
},
{
"id": "13220",
"image_type": "MediumImage",
"is_primary": "0"
},
{
"id": "13221",
"image_type": "LargeImage",
"is_primary": "0"
}
]
我想把这个转换成这个:
[
"ThumbnailImage" => [
{
"id": "13216",
"image_type": "ThumbnailImage",
"is_primary": "1"
},
{
"id": "13219",
"image_type": "ThumbnailImage",
"is_primary": "0"
},
],
"MediumImage" => [
{
"id": "13217",
"image_type": "MediumImage",
"is_primary": "1"
},
{
"id": "13220",
"image_type": "MediumImage",
"is_primary": "0"
},
],
"LargeImage" => [
{
"id": "13218",
"image_type": "LargeImage",
"is_primary": "1"
},
{
"id": "13221",
"image_type": "LargeImage",
"is_primary": "0"
}
]
]
我正在寻找动态解决方案,我可以在其中指定键名,它会根据该索引的值自动分离数组,例如在这种情况下,如果我指定索引名称 image_type,它应该给我提到的输出,如果我指定 is_primary,它应该 return 索引 0 和 1 及其值。
最终解决方案:
public function segregateByIndex($array, $segregateKey)
{
$result = [];
foreach( $array as $val ) {
$result[$val[$segregateKey]][] = $val;
}
return $result;
}
使用 foreach
就像
一样很容易解决
$result = [];
foreach(json_decode($your_json,true) as $key => $val){
$result[$val['image_type']][] = $val;
}
print_r($result);
我有一个这样的数组:
[
{
"id": "13216",
"image_type": "ThumbnailImage",
"is_primary": "1"
},
{
"id": "13217",
"image_type": "MediumImage",
"is_primary": "1"
},
{
"id": "13218",
"image_type": "LargeImage",
"is_primary": "1"
},
{
"id": "13219",
"image_type": "ThumbnailImage",
"is_primary": "0"
},
{
"id": "13220",
"image_type": "MediumImage",
"is_primary": "0"
},
{
"id": "13221",
"image_type": "LargeImage",
"is_primary": "0"
}
]
我想把这个转换成这个:
[
"ThumbnailImage" => [
{
"id": "13216",
"image_type": "ThumbnailImage",
"is_primary": "1"
},
{
"id": "13219",
"image_type": "ThumbnailImage",
"is_primary": "0"
},
],
"MediumImage" => [
{
"id": "13217",
"image_type": "MediumImage",
"is_primary": "1"
},
{
"id": "13220",
"image_type": "MediumImage",
"is_primary": "0"
},
],
"LargeImage" => [
{
"id": "13218",
"image_type": "LargeImage",
"is_primary": "1"
},
{
"id": "13221",
"image_type": "LargeImage",
"is_primary": "0"
}
]
]
我正在寻找动态解决方案,我可以在其中指定键名,它会根据该索引的值自动分离数组,例如在这种情况下,如果我指定索引名称 image_type,它应该给我提到的输出,如果我指定 is_primary,它应该 return 索引 0 和 1 及其值。
最终解决方案:
public function segregateByIndex($array, $segregateKey)
{
$result = [];
foreach( $array as $val ) {
$result[$val[$segregateKey]][] = $val;
}
return $result;
}
使用 foreach
就像
$result = [];
foreach(json_decode($your_json,true) as $key => $val){
$result[$val['image_type']][] = $val;
}
print_r($result);