我有一个像这样的JSON字符串,但是我不希望两次使用相同键的元素。
与第二个C
的情况一样,我希望将特定num
的{{1}}添加到父status
(就像新的合并C
应该status: 0
一样与num: 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()
输出了这个。这个问题可能重复,但我真的无法找到对我有用的东西。
答案 0 :(得分: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
)
)