Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

202
Visualizações
Format JSON conditionally

I'm trying to learn PHP and am just trying to generate some JSON

This is the format I want it in.

{
    "Data": "Message was sent on 12-31-1999 12:00:00 am",
    "Sandbox": {
        "Sandboxed": true
    },
    "Errors": [{
        "Code": 5,
        "Message": "Message bounced back"
    }]
}

And I can do that with :

$message = "Message was sent on 12-31-1999 12:00:00 am";
$errorMsg = "Message bounced back";

$sandboxkey = array( "Sandboxed" => true );

$error = array( "Code" => 5, "Message" => $errorMsg );

$package = array(
    "Data" => $message,
    "Sandbox" => $sandboxkey,
    "Errors" => $error
);

return json_encode($package, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

But I want to only add the "Sandbox" key/value if a boolean is set.

$isSandbox = true;
$message = "Message was sent on 12-31-1999 12:00:00 am";
$errorMsg = "Message bounced back";
$error = array( "Code" => 5, "Message" => $errorMsg );
$package = array(
    "Data" => $message,
    "Errors" => $error
);
if ($isSandbox) {
    $sandboxkey = array( "Sandboxed" => true );
    array_push($package, $sandboxkey);
}
$error = array( "Code" => 5, "Message" => $errorMsg );
return json_encode($package, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

But that adds a "0" then the KVP.

{
    "Data": "Message was sent on 12-31-1999 12:00:00 am",
    "Errors": {
        "Code": 5,
        "Message": "Message bounced back"
    },
    "0": {
        "Sandboxed": true
    }
}

Additionally, I want the Errors to be listed in an array like:

"Errors": [{
        "Code": 5,
        "Message": "Message bounced back"
    },
            {
        "Code": 4,
        "Message": "Message is old"
    }  ]

I have tried multiple combinations of array push, and JSON_FORCE_OBJECT but I just can't seem to get it exactly how I want. Can anyone help?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

But that adds a "0" then the KVP.

array_push() could be used if the array was a numeric array (i.e. the keys were integers - e.g. 0 => 'cat', 1 => 'dog'. But in this case, the array is an associative array. One way to set the desired key, Sandbox, is to set the array key by specifying it in bracket notation:

if ($isSandbox) {
    $sandboxkey = array( "Sandboxed" => true );
    $package['Sandbox'] = $sandboxkey;
}

This is necessary because the other keys of the array are not

See it demonstrated in this playground example.

Otherwise array_merge() could be used:

if ($isSandbox) {
    $sandboxArray = array(
    'Sandbox' => array( "Sandboxed" => true )
    );
    $package = array_merge($package, $sandboxArray);
}

See a demonstration in this playground example.

Refer to this answer for more information about numeric vs associative arrays. It is somewhat surprising that the difference isn't explicitly spelled out on the PHP Array data type page.

Additionally, I want the Errors to be listed in an array...

For this, nest $error (an associative-array, which will get converted to a JSON object) in another array.

$package = array(
    "Data" => $message,
    "Sandbox" => $sandboxkey,
    "Errors" => array($error)
);
over 4 years ago · Santiago Trujillo Relatório

0

You have to make few changes in your code, which will help you achieve your expected output.

1. Use array_merge instead of array_push

2. Set Errors key like this "Errors" => array($error) instead of "Errors" => $error

Try this code snippet here

<?php

ini_set('display_errors', 1);
$isSandbox=true;
$message = "Message was sent on 12-31-1999 12:00:00 am";
$errorMsg = "Message bounced back";
$error = array("Code" => 5, "Message" => $errorMsg);
$package = array(
    "Data" => $message,
    "Errors" => array($error)
);
if ($isSandbox)
{
    $sandboxkey = array("Sandboxed" => true);
    $package=array_merge($package, $sandboxkey);
}
echo json_encode($package,JSON_PRETTY_PRINT);

Output:

{
    "Data": "Message was sent on 12-31-1999 12:00:00 am",
    "Errors": [
        {
            "Code": 5,
            "Message": "Message bounced back"
        }
    ],
    "Sandboxed": true
}
over 4 years ago · Santiago Trujillo Relatório

0

How to handle json:

  • [] are arrays in json
  • {} are objects in json

So to create something like {'data':[{'depperdata':2}]} do

 $a = new stdClass();
 $a->data = array();
 $b = new stdClass();
 $b->deeperdata=2;
 $a->data[0]=$b;
 print_r(json_encode($a,JSON_PRETTY_PRINT));

or

 $a = array('data'=>array(array('depperdata'=>2)));
 print_r(json_encode($a,JSON_PRETTY_PRINT));

What does json_decode

  • if you have an assoc-array it becomes an json_object
  • if you have an indexed array it becomes an json_array
  • if you have an object it becomes an json_object
  • if you have mixed assoc/index array you are getting broken json like your example. property name 0! (prevent that!)

Have a nice day...

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda