Return specific array value in json format using php

how to get data from json array in php
php json_encode(array of objects)
php array to json
php array to json online
create json array in php loop
php array to javascript object
php json foreach key => $value
php parse json array of objects

I want to display an output illustrated as json format but using PHP. I have an array for fruits and its color.

Array list

red = apple, strawberry

yellow = lemon, ripe mango

  <?php
  class FruitColor
  {
  private $fruitcolor;
  function FruitColor($fruitcolor)
  {
  $this->fruitcolor = $fruitcolor;
  }

  public function getFruits($color)
  {

  return NULL;
  }
  }

  $fruitcolor = new FruitColor(array(
"red" => array("apple", "strawberry"),
"yellow" => array("lemon", "ripe mango")
 ));

 echo $fruitcolor->getFruits("red");
 echo "\n";
 echo $fruitcolor->getFruits("violet");


 ?>

As you can see, this line echo $fruitcolor->getFruits("red"); represents red Where the output should be like this

{ "color":"red", "fruits": ["apple", "strawberry"]}

and if there's no color like violet in the array, the output should be like this

{ "color":"violet", "fruits":[] }

This way of coding like json is new to me. I guess i should use IF ELSE statement on this problem? But I dont know how can I implement it.

You can use json encode to do that. First you have to check if there is any fruits or not.

$fruits = isset($this->fruitcolor[$color]) ? $this->fruitcolor[$color] : array();

it's a shorthand version of if else statement which will return the fruits list if exists otherwise an empty array. Then you can encode that result using json_encode.

class FruitColor
{
    private $fruitcolor;

    function __construct($fruitcolor)
    {
        $this->fruitcolor = $fruitcolor;
    }

    public function getFruits($color)
    {
        $fruits = isset($this->fruitcolor[$color]) ? $this->fruitcolor[$color] : array();
        return array('color' => $color, 'fruits' => $fruits);
    }

    public function getFruitsJSON($color){
        return json_encode($this->getFruits($color));
    }
}

$fruitcolor = new FruitColor(array(
    "red" => array("apple", "strawberry"),
    "yellow" => array("lemon", "ripe mango")
));

echo $fruitcolor->getFruitsJSON("red");
echo "\n";
echo $fruitcolor->getFruitsJSON("violet");

Here getFruits will return the data as php array and getFruitsJSON will return that array as JSON encoded string.

WARNING: using same classname to declare constructor is deprecated, use __construct instead.

Get values from JSON array in PHP with the following format , First of all you have not a json-structure inside the "data" field, but just a string, which contains json data. Therefore you did it wrong, when� Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.

I'm not sure if I understand you. Normally what you do is going through serializer that serialize an object(in your case FruitColor) to some representation ex. JSON. What you want to do is that a method returns a json string which breaks SRP for sure but just for education let me help you with that.

  class FruitColor
  {
     private $fruitColors;

     public function __construct(array $fruitColors)
     {
         $this->fruitColors = $fruitColors;
     }

     public function getFruits(string $color): string
     {
         return json_encode([
             'color' => $color,
             'fruits' => $this->fruitColors[$color] ?? []
         ]);   
     }
  }  

  $fruitcolor = new FruitColor([
    "red"    => ["apple", "strawberry"],
    "yellow" => ["lemon", "ripe mango"],
  ]);

 echo $fruitcolor->getFruits("red");
 echo "\n";
 echo $fruitcolor->getFruits("violet");

The other better approach would be not to use json_encode in getFruits but use it on an array that is returned by this method.

Pass PHP Arrays to JSON and JavaScript Using json_encode, The PHP json_encode function returns a string containing the JSON equivalent of the value passed to it as we demonstrate here with a numerically indexed array:. Convert the request into an object, using the PHP function json_decode(). Access the database, and fill an array with the requested data. Add the array to an object, and return the object as JSON using the json_encode() function. Loop Through the Result

Something like so....

<?php

class FruitColor
{
    private $fruitcolor = array ( );

    public function __construct ( $fruitcolor )
    {
        $this->fruitcolor = $fruitcolor;
    }

    public function getFruits ( $color )
    {
        return json_encode ( array ( 'color' => $color, 'fruits' => array ( ( ! empty ( $this->fruitcolor[$color] ) ? $this->fruitcolor[$color] : '' ) ) ) );
    }
}

  $fruitcolor = new FruitColor ( array ( 'red' => array ( 'apple', 'strawberry' ), 'yellow' => array ( 'lemon', 'ripe mango' ) ) );

 echo $fruitcolor->getFruits ( 'red' ) . "\r\n";

 echo $fruitcolor->getFruits ( 'violet' ) . "\r\n";


 ?>

json_encode - Manual, Returns a string containing the JSON representation of the supplied value . Example #2 A json_encode() example showing some options in use JSON that is a simple value (that is, neither an object nor an array) if given a string, integer, � Encoding JSON Data in PHP. In PHP the json_encode() function is used to encode a value to JSON format. The value being encoded can be any PHP data type except a resource, like a database or file handle. The below example demonstrates how to encode a PHP associative array into a JSON object:

How to create an array for JSON using PHP?, Multidimensional arrays. For these purpose we will use associative array that uses a key value type structure for storing data. These key will be a string or an� In a high-voted example, an array is given that contains, amongst other things, true, false and null, against which various variables are tested using in_array and loose checking. It impossible to receive false as a return value from in_array using loose checking if your arrays contains both the constants true and false.

Convert and Loop through JSON with PHP and JavaScript Arrays , Convert JSON String to PHP Array or Object PHP >= 5.2. 0 features a function, json_decode , that decodes a JSON string into a PHP variable. By default it returns an object. The second parameter accepts a boolean that when set as true , tells it to return the objects as associative arrays. Like the reference JSON encoder, json_encode() will generate JSON that is a simple value (that is, neither an object nor an array) if given a string, integer, float or boolean as an input value. While most decoders will accept these values as valid JSON, some may not, as the specification is ambiguous on this point.

JSON PHP, PHP File explained: Convert the request into an object, using the PHP function json_decode(). Access the database, and fill an array with the requested data. Add the array to an object, and return the object as JSON using the json_encode() function. A note of caution: If you are wondering why json_encode() encodes your PHP array as a JSON object instead of a JSON array, you might want to double check your array keys because json_encode() assumes that you array is an object if your keys are not sequential.

Comments
  • php.net/manual/en/function.json-encode.php???
  • hello sir I tried to put this echo json_encode($fruitcolor); to getFruits function it returns "null null"
  • Short note: coalescing operator (??) introduced in PHP 7.0 . It might throw an error if someone tried to run this on php 5x.
  • This works fine to me. Sir lfty maybe got a point when the codes tried to run in older version can appear a problem. my knowledge in php not that deep but how can I avoid that error in the future?
  • 'fruits' => isset($this->fruitColors[$color]) ? $this->fruitColors[$color] : []
  • There is no problem if you run php 7. Some shared hosting still doesn't support php7. In that case they need to do this using the old fashioned way ( isset ). If you are running php7, its fine.
  • PHP 5.x is not supported anymore even 7.0 is not supported. php.net/supported-versions.php If you are on a hosting that doesn't support it I would run away from that hosting because it's just not secure