【问题标题】:formatting an array of array that contain similar key value格式化包含相似键值的数组数组
【发布时间】:2020-07-08 07:08:36
【问题描述】:

我有一组像这样的数组

array(4) {
  [0] => array(2) {
    ["option"] => string(5) "64310"
    ["choice"] => string(6) "221577"
  }
  [1] => array(2) {
    ["option"] => string(5) "64310"
    ["choice"] => string(6) "221578"
  }
  [2] => array(2) {
    ["option"] => string(5) "64305"
    ["choice"] => string(6) "221538"
  }

}

我想得到这样的结果

array(2) {
  [0] => array(2) {
    ["option"] => string(5) "64310"
    ["choices"] => array(2){
       ["choice"] => string(6) "221577"
       ["choice"] => string(6) "221578"
    }
  }
}

我该如何继续,提前谢谢你

【问题讨论】:

  • 一个简单的 foreach 就可以完成这项工作。到目前为止,您尝试了什么?
  • array(2) { [0] => array(2) { ["option"] => string(5) "64310" ["choices"] => array(2){ ["choice"] => string(6) "221577" ["choice"] => string(6) "221578" } } }
  • 您刚刚在 cmets 中再次粘贴了您想要的结果。请编辑问题以添加您编写的尝试实现此目的的代码。
  • 在您的问题底部有一个小的“编辑”链接,您可以使用它来添加更多信息。注释不适合多行代码。
  • $result=$array[0]; $options = []; foreach ($array as $value){ if(isset($result[$value["option"]]) && !in_array($result[$value["option"]], $options) ){ array_push($options, $result[$value["option"]]); } }

标签: php


【解决方案1】:

这样的事情会帮助你达到预期的结果;

<?php

    $data = [
        [
            'option' => '64310',
            'choice' => '221577'
        ],
        [
            'option' => '64310',
            'choice' => '221578'
        ],
        [
            'option' => '64305',
            'choice' => '221538'
        ]
    ];

    $res = [];
    foreach($data as $d) {

        // Check if we've already got this option
        // Note the '&' --> Check link below
        foreach($res as &$r) {
            if (isset($r['option']) && $r['option'] === $d['option']) {

                // Add to 'choices'
                $r['choices'][] = $d['choice'];

                // Skip the rest of both foreach statements
                continue 2;
            }
        }

        // Not found, create
        $res[] = [
            'option' => $d['option'],
            'choices' => [ $d['choice'] ],
        ];
    };

    print_r($res);

&amp; --> PHP "&" operator

Array
(
    [0] => Array
        (
            [option] => 64310
            [choices] => Array
                (
                    [0] => 221577
                    [1] => 221578
                )
        )
    [1] => Array
        (
            [option] => 64305
            [choices] => Array
                (
                    [0] => 221538
                )
        )
)

Try online!

【讨论】:

  • @치노장인 很高兴它成功了!您是否关注了&amp; 链接?很重要的素材哈哈!另外,请accept the answer,您认为这是您问题的最佳解决方案,以便其他 SO 用户可以找到解决方案;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-29
  • 1970-01-01
  • 2017-05-01
  • 1970-01-01
相关资源
最近更新 更多