根据数组

时间:2015-08-22 21:58:55

标签: php arrays json

我有一个像这样的json数组:

"spellsCount": [
    {
      "value": 0,
      "globalID": 26000000
    },
    {
      "value": 0,
      "globalID": 26000001
    },
    {
      "value": 0,
      "globalID": 26000002
    },
    {
      "value": 0,
      "globalID": 26000003
    },
    {
      "value": 0,
      "globalID": 26000005
    },
    {
      "value": 0,
      "globalID": 26000009
    },
    {
      "value": 0,
      "globalID": 26000011
    }
  ],

现在我需要做的是制作一个php循环或其他会遍历整个数组并使值为0的变量;

现在棘手的是,并非所有GlobalID都显示在该数组中。例如,26000010未显示。

我需要它来制作变量 $spells26000000 = 0; 对于每个项目。包括介于两者之间但缺失的那些。因此,如果使用上述数组,也会有变量$spells26000010 = 0;

最初我有这个:

for ($i=0; $i < 100; $i+=1){// start at index 0 (1st value) and increment by 1
    if (isset($data['spellsCount'][$i])) {  // just in case there aren't actually 100
        // Use variable variables to create the $achievement variables you want
        $globalID = $data['spellsCount'][$i]['globalID'];
        ${"spells$globalID"} = $data['spellsCount'][$i]['value'];
    }
}

但后来我意识到有些价值观并不总是显示出来,所以我想我需要这样做,但我不知道该怎么做。

顺便说一下!我正在使用json_decode这样$data = json_decode($jsondata, true);

1 个答案:

答案 0 :(得分:0)

<?php
$data = json_decode(data(), true);
$spellsCounts = [];
// make the globalID the index of each respective element
foreach($data['spellsCount'] as $sc) {
    $spellsCounts[ $sc['globalID'] ] = $sc;
}
// sort the elements by ascending key (i.e. globalID)
ksort($data);

// run from first.globalID==min to end.globalID==max
$min = reset($spellsCounts)['globalID']; // Function array dereferencing has been added in php 5.4
$max = end($spellsCounts)['globalID'];
for($i=$min; $i<=$max; $i++) {
    // ....but this just doesn't sound right
    // it's just polluting the namespace
    ${'spells'.$i} = isset($spellsCounts[$i]) ? $spellsCounts[$i]['value'] : 'n/a';
}

// how about using the $spellsCount array
// and fill it up with the missing values ( in case you really need that) ?
for($i=$min; $i<=$max; $i++) {
    // ....but this just doesn't sound right
    if ( !isset($spellsCounts[$i]) ) {
        $spellsCounts[$i] = [
            'globalID' => $i,
            'value' => 'n/a'
        ];
    }
}
var_dump($spellsCounts);



function data() {
    return '{"spellsCount": [
    {
      "value": 0,
      "globalID": 26000000
    },
    {
      "value": 0,
      "globalID": 26000001
    },
    {
      "value": 0,
      "globalID": 26000002
    },
    {
      "value": 0,
      "globalID": 26000003
    },
    {
      "value": 0,
      "globalID": 26000005
    },
    {
      "value": 0,
      "globalID": 26000009
    },
    {
      "value": 0,
      "globalID": 26000011
    }
  ]}';
}