String object to array php

Wonder, I get from some API the following string:

parseresponse({"eurusd":{ "id": "eurusd", "category": "Forex", "price": 1.3161, "name": "EUR/USD", "buy": 1.3162, "sell": 1.3159, "change": 0.00, "date":1328288216000}});

for some reason I can't replace it to Array when I using:

var_dump(json_decode($content));

and I trying with php function also:

function object2array($object) {
if (is_object($object)) foreach ($object as $key => $value) $array[$key] = $value;
    else $array = $object;
return $array;
}

any idea?..

asked Feb 5, 2012 at 8:35

You're trying to parse JSONP response as JSON, you should remove wrapping function first.

$response = 'parseresponse({"eurusd":{ "id": "eurusd", "category": "Forex", "price": 1.3161, "name": "EUR/USD", "buy": 1.3162, "sell": 1.3159, "change": 0.00, "date":1328288216000}});';
$json = preg_replace('/^parseresponse\((.*)\);/', '$1', $response);
$data = json_decode($json, true);
print_r($data);

answered Feb 5, 2012 at 8:44

Juicy ScripterJuicy Scripter

25.5k6 gold badges72 silver badges91 bronze badges

1

You could try something like this:

$content = '{"eurusd":{ "id": "eurusd", "category": "Forex", "price": 1.3161, "name": "EUR/USD", "buy": 1.3162, "sell": 1.3159, "change": 0.00, "date":1328288216000}}';

function toArray($data) {
    if (is_object($data)) $data = get_object_vars($data);
    return is_array($data) ? array_map(__FUNCTION__, $data) : $data;
    }

$newData = toArray (json_decode($content));

print_r($newData);

output will be:

Array ( [eurusd] => Array ( [id] => eurusd [category] => Forex [price] => 1.3161 [name] => EUR/USD [buy] => 1.3162 [sell] => 1.3159 [change] => 0 [date] => 1328288216000 )

)

answered Feb 5, 2012 at 9:02

PHP is one of the most popular general-purpose scripting languages used widely for web development. It is one of the fastest and flexible programming languages. Working with PHP is all about dealing with data types. There are several data types in PHP in which objects and arrays are the composite data types of PHP. This article is centred on how to convert an object to array in PHP.

Check out our free technology courses to get an edge over the competition.

  • Object-Oriented Programming (OOP) in PHP
    • Some OOP Concepts
    • Class
    • Object
    • Example Defining a Class and its Objects
    • Array
    • Defining an Array
  • Object to Array PHP
    • 1. Typecasting Object to Array PHP
    • 2. Using the JSON Decode and Encode Method
  • Conclusion
  • What are the applications of PHP?
  • Why would one want to convert an object to an array in PHP?
  • What are the various principles of object-oriented programming?

Object-Oriented Programming (OOP) in PHP

One of the key aspects of PHP is object-oriented programming where the data is treated as an object, and software is implemented on it. This is one of the simplified approaches of advanced PHP. Object-oriented programming is achievable with PHP where objects have rules defined by a PHP program they are running in. These rules are called the classes. They are very important if you are looking to convert object to array in PHP. 

Check out upGrad’s Advanced Certification in Blockchain

Some OOP Concepts

Before getting into how objects are converted into arrays, let’s first learn about some important terms related to object-oriented programming in PHP.

Class

Classes are the data types defined by a programmer. It includes local function and local data. A class can serve as a template for making multiple instances of the same class of objects.

String object to array php

Object

An individual instance of the data structure is defined by a class. Many objects belonging to a class can be made after defining a class once. Objects are also called as instances.

Check out upGrad’s Java Bootcamp

Example Defining a Class and its Objects

class Jobs {

   // Members of class Jobs

}

// Creating three objects of Jobs

$software = new Jobs;

$pharmaceutical = new Jobs;

$finance = new Jobs;

Array

An array, in PHP, is a special kind of variable that holds more than one value at a time.

Defining an Array

In PHP, the array is defined with the array function ‘array()’.

Example:

$numbers = array(“One”, “Two”, “Three”);

echo count($numbers);

?>

Read: 15 Exciting PHP Project Ideas & Topics For Beginners

Object to Array PHP

There are mainly two methods by which an object is converted into an array in PHP:

1. By typecasting object to array PHP

2. Using the JSON Decode and Encode Method

Let’s have a look at both in detail:

1. Typecasting Object to Array PHP

Typecasting is a method where one data type variable is utilized into a different data type, and it is simply the exact conversion of a data type. It is also one of the most used methods of converting an object to array in PHP.

In PHP, an object can be converted to an array with the typecasting rules of PHP.

Syntax:

$myArray = (array) $myObj;

Program:

   class shop {

      public function __inventory( $product1, $product2, $product3){

         $this->product1 = $product1;

         $this->product2 =$product2;

         $this->product3 = $product3;

      }

   }

   $myShop= new shop(“Grocery”, “Cosmetic”, “Grain”);

   echo “Before conversion :”.'
’;

   var_dump($myShop);

   $myShopArray = (array)$myShop;

   echo “After conversion :”.'
’;

   var_dump($myShopArray);

?>

Output:

 Before conversion:

object(shop)#1 (3) { [“product1″]=> string(5) ” Grocery ” [“product2″]=> string(4) ” Cosmetic ” [“product3″]=> string(4) ” Grain ” }

After conversion:

array(3) { [“product1″]=> string(5) ” Grocery ” [“product2″]=> string(4) ” Cosmetic ” [“product3″]=> string(4) ” Grain ” }

 Explanation of the program:

In the above program, a class “shop” is created. In the ‘shop’ class, the function ‘inventory()’ is created. The function inventory() will be executed when an object is created.

The constructor will receive arguments provided when the object is created with a new keyword. In the first var_dump() expression, the object is printed. The second time, the object is type casted into an array using the type-casting procedure.

2. Using the JSON Decode and Encode Method

Object to array PHP is also done with the JSON decode and encode method. In this method, the json_encode() function returns a JSON encoded string for a given value. The json_decode() function accepts the JSON encoded string and converts it into a PHP array. This is a very popular method used to convert object to array PHP.

Syntax:

$myArray = json_decode(json_encode($object), true);

Program:

   class employee {

      public function __company($firstname, $lastname) {

         $this->firstname = $firstname;

         $this->lastname = $lastname;

      }

   }

   $myObj = new employee(“Carly”, “Jones”);

   echo “Before conversion:”.'
’;

   var_dump($myObj);

   $myArray = json_decode(json_encode($myObj), true);

   echo “After conversion:”.'
’;

   var_dump($myArray);

?>

Output:

Before conversion:

object(student)#1 (2) { [“firstname”]=> string(4) ” Carly ” [“lastname”]=> string(6) ” Jones ” }

After conversion:

array(2) { [“firstname”]=> string(4) ” Carly ” [“lastname”]=> string(6) ” Jones ” }

Explanation of the program:

In the program above, a class with the name ‘employee’ is created. In that class, a function ‘company()’ is declared which will be executed during the creation of the object.

The constructor receives the arguments given when creating the object using a new keyword. In the first var_dump() expression, the object is printed and in the second, the object is converted into an array using json_decode and json_encode technique.

How to create an Object from Array in PHP

PHP object to array and how to convert object to array PHP have been covered. We will now examine how to build an object from an array. You are free to use any of the distinct examples mentioned above for PHP object to array to do this in order to meet the demands of your own code.

Method 1 – 

Use json_decode and json_encode Method

The json decode() and json encode() methods in PHP may be used to create an object from an array, similar to changing an object to an array PHP. The array is first produced, and then it is transformed into an object. The array is transformed into an object using – 

$object = json_decode (json_encode ($array))

The output is then printed out using –

function var_dump(variable of the object)

For example – 

//Arrays of types of cars

$carArray = [

‘cars’ => [‘Benz’,  ‘BMW’,  ‘AUDI’]

];

//Convert array into an object

$object = json_decode(json_encode($carArray));

//Print array as an object using

var_dump($object);

?>

Output – 

object(stdClass)#1 (1) {

[“cars”] =>

array (3)  {

[0] =>

string(4)  “Benz”

[1] =>

string(3)  “BMW”

[2] =>

string(4) “AUDI”

}

Convert Associative Array into Object 

In this instance, an associative array is transformed into an object using the formula –

$object = (object) $array 

Finally, we use this method to print the output 

var_dump(variable of an object)

For Example 

//Arrays of types of cars

$carArray = array(

‘cars’ => [‘Benz’ , ‘BMW’ , ‘Audi’],

‘parts’ => [‘tyre’, ‘mirror’, ‘footmat’]

);

//Convert array into an object

$object = (object) $carArray;

//Print array as an object, all elements under $carArray

var_dump($object);

//Print array as an object, only elements within ‘parts’ in $carArray Array

var_dump($object ->parts)

?>

Output – 

object(stdClass)# (2) {

[“cars”] =>

array(3) {

[0] =>

string(4) “Benz”

[1] =>

string(3) “BMW”

[2] =>

string(4) “AUDI”

}

[“parts”] =>

array(3)  {

[0]=>

string(4) “tyre”

[1] =>

string(6) “mirror”

[2] =>

string(7) “footmat”

}

}

array(3)  {

[0]=>

string(4) “tyre”

[1] =>

string(6) “mirror”

[2] =>

string(7) “footmat”

}

Convert a Multidimensional Array to an Object

With this technique, a multidimensional array is transformed into an object by applying the formula 

$object = (object) $array 

Finally, we use this method to print out the variable 

var_dump (variable of an object)

For example – 

//Arrays of types of cars

$schoolArray = array(

“One” => Array(“student” =>’John Doe’),

“Two” => Array(“subject” => “Introduction to Computer Science’),

“Three” => Array(“grade” = ‘84’)

);

//Convert array into an object

$ibject = (object) $schoolArray;

//Print array as an object, all elements under $schoolArray

var_dump($object);

?>

Output – 

object(stdClass) #1 (3) {

[“one”]=>

array(1) {

[“student”]=>

string(8) “John Doe”

}

[“two”]=>

array(1) {

[“subject”] =>

string (32) “Introduction to Computer Science”

}

[“three”]=>

array(1) {

[“grade”] =>

string(2) “84”

}

}

array(1)  {

[“student”]=>

string(8)  “John Doe”

}

Convert Array to Object With Foreach Loop 

When you wish to turn an array into an object, you may apply the same technique as mentioned for PHP convert object to array, but this time try to use a foreach loop. Additionally, the array is turned into an object using the syntax 

$object = (object) $array

Finally, we use this method to print the variable 

var_dump(variable of an object)

For example 

//Array of school-related things

$schoolArray = array(

“one” => Array(“student” = > ‘John Doe’),

“two” => Array(“subject” => ‘Introduction to Computer Science’)

“three” => Array(“grade” => ‘84’)

);

$object = new stdClass();

//Using foreach loop

foreach ($schoolArray as $keys => $value)    {

$object -> {$keys} = $value;

}

//Print array as an object, all elements under $schoolArray

var_dump($object);

?>

Output 

object(stdClass)#1 (3) {

[“one”]=>

array(1)  {

[“student”]=>

string(8) “John Doe”

}

[“two”]=>

array(1)  {

[“subject”]=>

string(32) “Introduction to Computer Science”

}

[“three”]=>

array(1)  {

[“grade”]=>

string(2) “84”

String object to array php

}

}

Also Read: 15 Interesting PHP Projects on Github For Beginners

Conclusion

In this article, we have introduced one of the most prominent topics of PHP. As a programmer, you will be dealing with every aspect of the language and have to work on some of the most complicated PHP concepts when moving to the advanced level. Hope this article highlighting the methods for converting an object to array in PHP will prove out to be a reference point for you.

upGrad brings programming with PHP and a lot more with upGrad’s PG Diploma in Software Development Specialisation in Full Stack Development. A program to make you emerge as a full stack developer and learning to build some of the awesome applications. It is an extensive 12-months program that includes working on live projects and assignments and also training 15 programming languages and tools. Along with it, it has all-time career support with mock interviews and job assistance.

What are the applications of PHP?

PHP stands for HyperText Preprocessor. PHP is used to handle forms, connect to the database, send and retrieve data to and from the database, etc. PHP is simple, easy to learn, and integrates with other applications. It is used for making requests like GET, POST, PUT, DELETE, UPDATE, etc. It can be used to create APIs (Application Programming Interface). It also ensures the secure transfer of data by encrypting it. Also, session management can also be done in PHP using cookies and session objects. PHP is platform-independent. Some of the organizations that use PHP are Wikipedia, Slack, WordPress, etc.

Why would one want to convert an object to an array in PHP?

An array is a data structure that helps to store values. Each value in the array can be accessed through an index. An object is a compound data type that stores the values or properties of an element. Objects exhibit the properties of a class. Arrays provide a lot of functions that can be applied to the data. It helps in easier manipulation and easier extraction of useful data stored in the array. They are lightweight and simple. Hence, while writing code for some applications we might want to convert objects to an array.

What are the various principles of object-oriented programming?

Data Abstraction, Encapsulation, Inheritance, and Polymorphism are the principles of object-oriented programming. Data Abstraction deals with showing the user only what is necessary and hiding the unnecessary and trivial details. Encapsulation is a means of binding the common functionalities and objects with the same properties or attributes together in the form of a class. Inheritance is the process of gaining access to some features and properties of the parent class. It helps in the reusability of code and ensures modularity. Polymorphism means “many forms”. It's of 2 types: compile time and run time. Here, one function can have multiple implementations. All these features help us in writing clean code.

Want to share this article?

Land on Your Dream Job

UPGRAD AND IIIT-BANGALORE'S PG DIPLOMA IN FULL STACK

Learn More

How do I convert a string to an array in PHP?

PHP | str_split() Function The str_split() is an inbuilt function in PHP and is used to convert the given string into an array. This function basically splits the given string into smaller strings of length specified by the user and stores them in an array and returns the array.

How do you object an array in PHP?

Convert to an Object.
Step 1 – Encode it to a string. $object = json_encode($array); var_dump this object will get you something like: "{"items":["foo","bar"]}" ... .
Step 2 – Decode it to an Object. Now as we have a json string, we can use json_decode to convert and format this string in to an object. Let's try that..

How do I turn a string into an array?

In Java, there are four ways to convert a String to a String array:.
Using String. split() Method..
Using Pattern. split() Method..
Using String[ ] Approach..
Using toArray() Method..

How do you change an object to an array?

To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .