0

我有一个这样的 JSON 字符串,但是我不希望元素具有相同的键两次。就像在 second 的情况下C,我希望将num特定的status添加到父级中(就像新的组合C应该status: 0num: 60883(3223 + 57659) 一样)。基本上,C应该只在我的数组中出现一次。其余元素相同。

[
   {
      "C":[
         {
            "status":"0",
            "num":"3223"
         },
         {
            "status":"1",
            "num":"45186"
         },
         {
            "status":"2",
            "num":"8310"
         },
         {
            "status":"3",
            "num":"82"
         }
      ]
   },
   {
      "C":[
         {
            "status":"0",
            "num":"57659"
         },
         {
            "status":"1",
            "num":"3017"
         }
      ]
   },
   {
      "F":[
         {
            "status":"0",
            "num":"1506"
         },
         {
            "status":"1",
            "num":"31253"
         },
         {
            "status":"2",
            "num":"1660"
         },
         {
            "status":"5",
            "num":"1017"
         }
      ]
   },
   {
      "F":[
         {
            "status":"0",
            "num":"34024"
         },
         {
            "status":"1",
            "num":"2167"
         }
      ]
   }
]

我正在使用 PHP 推送值,在我将值推送到内部之前我可以做些什么以确保没有重复项?

PHP 代码类似于:

foreach ($Something as $something) {
    $data = array(
        'status' => $something->status,
        'num'    => $something->num,
    );

    $zone_data[$stringWhichIsGenerated][] = $data;  
}

// Probably I have to do something here...?
array_push($zone_parent, $zone_data);

从早上开始,我一直在尝试想出几种愚蠢的方法来解决它,但直到现在我还没有真正富有成效。

json_encode()在我的阵列上使用它来输出它。这个问题可能是重复的,但我真的找不到任何对我有用的东西。

4

1 回答 1

1

扩展我的评论,我认为防止问题有助于首先实际使数组独一无二,特别是当你很幸运在这里你实际上是在最初制作数组时。

测试数据

class Foo {
    public $status;
    public $num;

    public function __construct( $status, $num ) {
        $this->status = $status;
        $this->num = $num;
    }
}

function generateRandomString( $length = 10 ) {
    $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $ranString = '';
    for ($i = 0; $i < $length; $i++)
         $ranString .= $characters[rand(0, strlen($characters) - 1)];               
    return $ranString;
}

$Something = array();
for( $x = 0; $x < 3; $x++ ) {
    $Something[$x] = new Foo( $x, rand(0, 100));
}

保持唯一

$zone_data = array();
foreach( $Something as $something ) {
    $data = array(
       'status' => $something->status,
       'num'    => $something->num,
    );

    do { 
        $Key = generateRandomString( 1 );   
    } while (array_key_exists( $Key, $zone_data ));

    $zone_data[$Key][] = $data;
}

结果

[V] => Array
    (
        [0] => Array
            (
                [status] => 0
                [num] => 72
            )
    )
[C] => Array
    (
        [0] => Array
            (
                [status] => 1
                [num] => 75
            )
    )
[B] => Array
    (
        [0] => Array
            (
                [status] => 2
                [num] => 6
            )
    )
于 2013-10-15T21:21:02.857 回答