Skip to content
Advertisement

Best way or practice to assign values to array and then encode it to json in symfony

So currently I have this code:

//getting products
    $productsFirst = $this->productRepository->findBy(
        ['weather' => $conditionFirst],
        ['price' => 'ASC'],
        2
    );
    

    $productsSecond = $this->productRepository->findBy(
        ['weather' => $conditionSecond],
        ['price' => 'ASC'],
        2
    );

    $productsThird = $this->productRepository->findBy(
        ['weather' => $conditionThird],
        ['price' => 'ASC'],
        2
    );

    //serializing products
    $normalizers = [
        new ObjectNormalizer(),
    ];
    $encoders = [
        new JsonEncoder(),
    ];
    $serializer = new Serializer($normalizers, $encoders);
    $productsFirst = $serializer->serialize($productsFirst, format:'json',);
    $productsSecond = $serializer->serialize($productsSecond, format:'json',);
    $productsThird = $serializer->serialize($productsThird, format:'json',);
    


    $arr = array(
        $city => array(
            "weather_forecast" => $conditionFirst,
            "date" => $dateFirst,
            "product" => $productsFirst
        ),
        array(
            "weather_forecast" => $conditionSecond,
            "date" => $dateSecond,
            "product" => $productsSecond
        ),
        array(
            "weather_forecast" => $conditionThird,
            "date" => $dateThird,
            "product" => $productsThird
        )
    );

    
  
    return $arr = json_encode($arr, | JSON_PRETTY_PRINT);

And i’m getting this json response:

   {
    "London": {
        "weather_forecast": "clear",
        "date": "2021-06-08",
        "product": "[{"id":903,"sku":"6456909228","name":"Abdul Bergstrom","price":0.45,"weather":"clear"},{"id":1074,"sku":"6540442971","name":"Gladys Kirlin","price":6.73,"weather":"clear"}]"
    },
    "0": {
        "weather_forecast": "clear",
        "date": "2021-06-09",
        "product": "[{"id":903,"sku":"6456909228","name":"Abdul Bergstrom","price":0.45,"weather":"clear"},{"id":1074,"sku":"6540442971","name":"Gladys Kirlin","price":6.73,"weather":"clear"}]"
    },
    "1": {
        "weather_forecast": "light-rain",
        "date": "2021-06-10",
        "product": "[{"id":1103,"sku":"8486705088","name":"Dr. Aniyah Stehr IV","price":1.62,"weather":"light-rain"},{"id":931,"sku":"3629804527","name":"Jean Kirlin","price":5.11,"weather":"light-rain"}]"
    }
}

But I would like to get rid of id and weather from the json. Decoding and then encoding again seems like a bad way to do it. Can I access needed values before serializing them to json? I would like to get something like this:

{
"London": {
    "weather_forecast": "clear",
    "date": "2021-06-09",
    "product": [
            {
                "name": "Dr. Aniyah Stehr IV",
                "sku": "8486705088",
                "price": "94.68"
            },
            {
                "name": "Jean Kirlin",
                "sku": "3629804527",
                "price": "10.76"
            }
},
"0": {
    "weather_forecast": "clear",
    "date": "2021-06-09",
    "product": [
            {
                "name": "Dr. Aniyah Stehr IV",
                "sku": "8486705088",
                "price": "94.68"
            },
            {
                "name": "Jean Kirlin",
                "sku": "3629804527",
                "price": "10.76"
            }

Sorry if it’s a dumb question i’m still getting the ropes of symfony.

Advertisement

Answer

You won’t need to serialiaze your array of entities.

In your entity you can declare

use JsonSerializable;

/**
* @Entity(repositoryClass="AppEntityMyEntity::class")
* @Table(name="user")
*/
class MyEntity implements JsonSerializable
{
    /** @Column(length=50) */
    private $name;

    /** @Column(length=50) */
    private $sku;

    /** @Column(length=50) */
    private $price;

    public function jsonSerialize()
    {
        return array(
            'name' => $this->name,
            'sku'=> $this->sku,
            'price'=> $this->price,
        );
    }
}

And then call in your code, you can directly call json_encode on those entities:

//getting products
$productsFirst = $this->productRepository->findBy(
    ['weather' => $conditionFirst],
    ['price' => 'ASC'],
    2
);


$productsSecond = $this->productRepository->findBy(
    ['weather' => $conditionSecond],
    ['price' => 'ASC'],
    2
);

$productsThird = $this->productRepository->findBy(
    ['weather' => $conditionThird],
    ['price' => 'ASC'],
    2
);

$arr = array(
    $city => array(
        "weather_forecast" => $conditionFirst,
        "date" => $dateFirst,
        "product" => $productsFirst
    ),
    array(
        "weather_forecast" => $conditionSecond,
        "date" => $dateSecond,
        "product" => $productsSecond
    ),
    array(
        "weather_forecast" => $conditionThird,
        "date" => $dateThird,
        "product" => $productsThird
    )
);



return $arr = json_encode($arr, | JSON_PRETTY_PRINT);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement