3w PHP Your Source for PHP Source Code

11Oct/100

How to convert array to object

When you want to convert array to object, you will usually use a named(associative) array rather then numbered array...

Example:

<?php
 
$users = array();
$users['mark_long'] = array(
					'id' => 1 ,
					'firstname' => 'Mark',
					'lastname' => 'Long',
					'phone' => '718-555-5555'
				);
$users['john_smith'] = array(
					'id' => 2 ,
					'firstname' => 'John',
					'lastname' => 'Smith',
					'phone' => '718-555-5555'
				);
$users['sam_jonson'] = array(
					'id' => 3 ,
					'firstname' => 'Sam',
					'lastname' => 'Jonson',
					'phone' => '718-555-5555'
				);
foreach ($users as $username => $user_data)
{
	$user_data = (object)$user_data;
	//// now we can access he data using the object...
	//// so instead of using $user_data['firstname'], 
	//// we will be using $user_data->firstname ...
 
	echo 'User ID: '. $user_data->id .'<br />' ;
	echo 'Full Name: '.$user_data->firstname .' ' . $user_data->lastname .'<br />';
	echo 'Phone Number: '.$user_data->phone .'<br />' ;
 
}
 
?>

Well, here we just did something very simple...
Feel free to comment on this, or ask any questions you might have.
Thank you.

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

No trackbacks yet.