Home > Software design >  PHP counting nodes in JSON returns to many
PHP counting nodes in JSON returns to many

Time:07-09

$ONEANSWER = '{
  "name": "Attendee terms and conditions",
  "id": "1z6wzmd95",
  "numberofcolumns": "1",
  "type": "check-box",
  "answers": {
    "answer": {
      "@attributes": {
        "code": "1z6x061vg",
        "revision": "8969663434"
      },
      "name": "Attendee terms and conditions",
      "sort": "0",
      "type": "label"
    }
  }
}';

$THREEANSWERS ='{
  "name": "GPP What printing are you responsible for (please select all that apply)?",
  "id": "1ygc0dvbi",
  "numberofcolumns": "2",
  "type": "check-box",
  "answers": {
    "answer": [
      {
        "@attributes": {
          "code": "1yx7dx07w",
          "revision": "8986379556"
        },
        "name": "Advertising - posters / signage",
        "sort": "0",
        "type": "label"
      },
      {
        "@attributes": {
          "code": "1ygc0eaqt",
          "revision": "8986379550"
        },
        "name": "Books and photo books",
        "sort": "1",
        "type": "label"
      },
      {
        "@attributes": {
          "code": "1yx7dx07y",
          "revision": "8986379557"
        },
        "name": "Décor",
        "sort": "2",
        "type": "label"
      }
    ]
  }
}';


$ONEANSWER =json_decode($ONEANSWER, true);
$THREEANSWERS  =json_decode($THREEANSWERS , true );

echo count($ONEANSWER['answers']);  //expect 1 get 1
echo count($ONEANSWER['answers']['answer']);  //expect 1 get 4

echo count($THREEANSWERS ['answers']); //expect 1 get 1
echo count($THREEANSWERS ['answers']['answer']); //expect 3 get 3

Running the above returns 4 but I am expecting 1. There is 1 'array->answers->answer' node so how come I get 4?

I have exactly the same JSON format with multiple 'answers' and the same approach is returning the right amount. Just seems to fail when there is one answer?

Thanks

CodePudding user response:

OK just for reference so as per multiple comments the 'answer' node is formatted differently in the response JSON if there are more than one 'answers' note the square brackets on the multiple answer example.

Setting the one answer to an array got it to work

echo count(array($ONEANSWER['answers']['answer'])); //expect 1 get 1

in production I can just check if it is an array and if not make it one.

CodePudding user response:

If it's associative array make it sequential array

function isAssoc($array) {
    $array = array_keys($array);
    return ($array !== array_keys($array));
}

if (isAssoc($ONEANSWER['answers']['answer'])) {
    $ONEANSWER['answers']['answer'] = [$ONEANSWER['answers']['answer']];
}
if (isAssoc($THREEANSWERS['answers']['answer'])) {//it's not associative array
    $THREEANSWERS['answers']['answer'] = [$THREEANSWERS['answers']['answer']];
}

using isAssoc

  • Related