从PHP中的多维关联数组中仅删除键

时间:2019-03-23 16:36:30

标签: php multidimensional-array

我想只从多维关联数组中删除键,以在PHP中保留其值。

我已经尝试过foreach循环。

foreach($collections as $k=>$v){
            foreach($v as $k1=>$v1){
                foreach($v1 as $k2=>$v2){
                    if($k2 == 'attr_id'){
                        unset($collections[$k][$k1][$k2]);
                    }
                }
            }
        }

我有一个如下数组:

$collections = [
            0 => [
                0 => [
                    "attr_id" => 23,
                    "value" => "Single Side"
                ],
                1 => [
                    "attr_id" => 23,
                    "value" => "Double Side"
                ],
            ],
            1 => [
                0 => [
                    "attr_id" => 31,
                    "value" => "A4"
                ],
                1 => [
                    "attr_id" => 31,
                    "value" => "12x18"
                ],
                2 => [
                    "attr_id" => 31,
                    "value" => "B5"
                ],
                3 => [
                    "attr_id" => 31,
                    "value" => "A5"
                ]
            ]
        ];

我想要这样的输出:

$collections = [
            23 => [ "Single Side", "Double Side" ],
            31 => [ "A4", "12x18", "B5", "A5" ]
        ];

请帮助!

3 个答案:

答案 0 :(得分:2)

简短解决方案:

$expected = [];
foreach ($collections as $collection) {
    $expected[$collection[0]['attr_id']] = array_column($collection, 'value');
}

答案 1 :(得分:0)

您只需使用两个foreach()循环并将推送到 attr_id

$expected = [];        
foreach($collections as $k=>$v){
    foreach($v as $k1=>$v1){
        $expected[$v1['attr_id']][] = $v1['value'];
    }
}
print_r($expected); 

输出:

Array (
   [23] => Array ( 
            [0] => Single Side 
            [1] => Double Side 
          ) 
   [31] => Array ( 
            [0] => A4 
            [1] => 12x18
            [2] => B5
            [3] => A5 
         )
    )

演示: https://3v4l.org/JlsIl

答案 2 :(得分:0)

使用array_reduceattr_id

  1. 首先将所有子数组合并到一个数组
  2. 根据$res = call_user_func_array('array_merge',array_values($arr)); $res = array_reduce($res,function($a,$b){ $a[$b['attr_id']] = isset($a[$b['attr_id']]) ? $a[$b['attr_id']] : [] ; array_push($a[$b['attr_id']],$b['value']); return $a; },[]); print_r($res); 匹配,使用reduce来附加值

Sandbox demo

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import preprocessing

data = pd.read_csv('gpmd.csv', header = 0)

X = data.loc[:, ['ContextID', 'BacksGas_Flow_sccm']]

min_max_scaler = preprocessing.MinMaxScaler()
X_minmax = min_max_scaler.fit_transform(X.values[:,[1]])

import scipy.cluster.hierarchy as sch
dendrogram = sch.dendrogram(sch.linkage(X_minmax, method = 'ward'))