简体   繁体   English

基于键对多维数组中的值进行分组

[英]Group values in multi-dimensional array based on a key

I have the following multi-dimensional array:我有以下多维数组:

Array
(
    [0] => Array
        (
        [sname] => florida
        [cname] => orlando
        )

    [1] => Array
        (
        [sname] => texas
        [cname] => dallas
        )

    [2] => Array
        (
        [sname] => florida
        [cname] => tampa
        )

    [3] => Array
        (
        [sname] => ohio
        [cname] => columbus
        )

)

How would I go about trying to get all ' cname ' values associated with each ' sname ' value?我将如何尝试获取与每个“ sname ”值相关联的所有“ cname ”值?

florida:    orlando, tampa
texas:      dallas
ohio:       columbus

With a slight tweak of Mike's solution ( https://stackoverflow.com/a/2189916/4954574 ), the following will produce what I was hoping for:稍微调整 Mike 的解决方案( https://stackoverflow.com/a/2189916/4954574 ),以下将产生我所希望的:

$input_arr = array(
    array("sname" => "florida", "cname" => "orlando"),
    array("sname" => "texas", "cname" => "dallas"),
    array("sname" => "florida", "cname" => "tampa"),
    array("sname" => "ohio", "cname" => "columbus")
);

foreach ($input_arr as $key => &$entry) {
    $level_arr[$entry['sname']][$key] = $entry['cname'];
}

print_r($level_arr);

Output:输出:

Array
(
    [florida] => Array
        (
            [0] => orlando
            [2] => tampa
        )

    [texas] => Array
        (
            [1] => dallas
        )

    [ohio] => Array
        (
            [3] => columbus
        )

)

There are probably several ways to do this.可能有几种方法可以做到这一点。 The one that comes to mind is something like this:想到的是这样的:

<?php

$payload = [];
$origin = [
    [
        'sname' => 'florida',
        'cname' => 'orlando'
    ],
    [
        'sname' => 'texas',
        'cname' => 'dallas'
    ],
    [
        'sname' => 'florida',
        'cname' => 'tampa'
    ],
    [
        'sname' => 'ohio',
        'cname' => 'columbus'
    ]
];


foreach ($origin as $value) {
  if (! isset($payload[$value['sname']])) {
    $payload[$value['sname']] = '';
  }

  $payload[$value['sname']] .= (strlen($payload[$value['sname']]) >0?',':'') . $value['cname'];
}

print_r($payload);

Cheers!干杯! :) :)

=C= =C=

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM