How to loop a foreach on an object/array - php

My DB returns an array of objects with arrays within.
Var_dump
array (size=2)
0 =>
object(stdClass)[22]
public 'customer_id' => string '10' (length=2)
public 'cart' => string 'a:1:{s:32:"f9bb1d342b1c2a0bfe982ef405369ec0";a:9:{s:5:"rowid";s:32:"f9bb1d342b1c2a0bfe982ef405369ec0";s:2:"id";s:9:"101_30524";s:3:"qty";s:1:"1";s:5:"price";s:5:"104.5";s:4:"name";s:13:"Business Card";s:5:"image";s:18:"business-cards.gif";s:4:"ship";a:3:{s:6:"Ground";d:9.730000000000000426325641456060111522674560546875;s:11:"2nd Day Air";d:18.53999999999999914734871708787977695465087890625;s:9:"Overnight";d:26.269999999999999573674358543939888477325439453125;}s:7:"options";a:2:{s:17:"Print Description";s:16'... (length=761)
public 'shipping_type' => string 'Ground' (length=6)
public 'shipping_cost' => string '9.73' (length=4)
public 'order_sub_total' => string '104.50' (length=6)
public 'order_total' => string '114.23' (length=6)
public 'id' => string '28' (length=2)
public 'timestamp' => string '2012-10-12 20:10:30' (length=19)
1 =>
object(stdClass)[23]
public 'customer_id' => string '10' (length=2)
public 'cart' => string 'a:2:{s:32:"22d2d3d8584f6e0819c4e46af4d2fda2";a:9:{s:5:"rowid";s:32:"22d2d3d8584f6e0819c4e46af4d2fda2";s:2:"id";s:9:"101_94980";s:3:"qty";s:1:"1";s:5:"price";s:2:"64";s:4:"name";s:13:"Business Card";s:5:"image";s:18:"business-cards.gif";s:4:"ship";a:3:{s:6:"Ground";d:9.730000000000000426325641456060111522674560546875;s:11:"2nd Day Air";d:18.53999999999999914734871708787977695465087890625;s:9:"Overnight";d:26.269999999999999573674358543939888477325439453125;}s:7:"options";a:2:{s:17:"Print Description";s:164:"'... (length=1506)
public 'shipping_type' => string 'Ground' (length=6)
public 'shipping_cost' => string '19.46' (length=5)
public 'order_sub_total' => string '148.25' (length=6)
public 'order_total' => string '167.71' (length=6)
public 'id' => string '29' (length=2)
public 'timestamp' => string '2012-10-12 20:29:10' (length=19)
Notice cart is a multidimensional array. How do I loop through these objects and arrays and create a table?
<?php foreach($all_orders as $key => $val) : ?>
<?php echo $key; ?> <?php echo $val; ?>
<?php endforeach; ?>
This causes the following error: A PHP Error was encountered Severity: 4096 Message: Object of class stdClass could not be converted to string

Access the properties of the stdClass object using the -> operator:
<?php foreach($all_orders as $key => $val) : ?>
Customer ID <?php echo $val->customer_id ?> has a total of <?php echo $val->order_total ?><br />
<?php endforeach ?>

You can try
echo "<pre>";
foreach ( $cart as $all_orders ) {
foreach ( $all_orders as $key => $value ) {
echo $key, " = ", $value, PHP_EOL;
}
}

PHP 5 allows one to iterate over an object's public properties using a foreach loop.
For more information (and code examples): http://php.net/manual/en/language.oop5.iterations.php

I use PHP's ArrayObject in my MVC:
us3.php.net/manual/en/class.arrayobject.php
$arrayobject = new ArrayObject($dataRows);
for ($iterator = $arrayobject->getIterator(); $iterator->valid(); $iterator->next()) {
}

Related

Access Special Character Key from STD array in PHP [duplicate]

I'm using a PHP class someone wrote to interface with the BaseCamp API.
The particular call I'm doing is to retrieve the items in a todo list, which works fine.
My problem is, I'm not sure how to access just the todo-items property of the object that is returned. Here's the var_dump of the returned object:
object(stdClass)[6]
public 'completed-count' => string '0' (length=1)
public 'description' => string 'Description String' (length=89)
public 'id' => string '12345' (length=7)
public 'milestone-id' => string '' (length=0)
public 'name' => string 'Error Reports' (length=13)
public 'position' => string '1' (length=1)
public 'private' => string 'false' (length=5)
public 'project-id' => string '58904' (length=7)
public 'tracked' => string 'false' (length=5)
public 'uncompleted-count' => string '1' (length=1)
public 'todo-items' =>
object(stdClass)[3]
public 'todo-item' =>
object(stdClass)[5]
public 'completed' => string 'false' (length=5)
public 'content' => string 'content string here' (length=133)
public 'created-on' => string '2009-04-16T20:33:31Z' (length=20)
public 'creator-id' => string '23423' (length=7)
public 'id' => string '234' (length=8)
public 'position' => string '1' (length=1)
public 'responsible-party-id' => string '2844499' (length=7)
public 'responsible-party-type' => string 'Person' (length=6)
public 'todo-list-id' => string '234234' (length=7)
public 'complete' => string 'false' (length=5)
How can I access the todo-items portion of this object?
<?php
$x = new StdClass();
$x->{'todo-list'} = 'fred';
var_dump($x);
So, $object->{'todo-list'} is the sub-object. If you can set it like that, then you can also read it the same way:
echo $x->{'todo-list'};
Another possibility:
$todolist = 'todo-list';
echo $x->$todolist;
If you wanted to convert it to an array, which can be a little more easily (ie the obvious $ret['todo-list'] accessing), this code is taken almost verbatim from Zend_Config and will convert for you.
public function toArray()
{
$array = array();
foreach ($this->_data as $key => $value) {
if ($value instanceof StdClass) {
$array[$key] = $value->toArray();
} else {
$array[$key] = $value;
}
}
return $array;
}
Try this simplest way!
$obj = $myobject->{'mydash-value'};
$objToArray = array($obj);

fetching data from JSON string using php * syntax [duplicate]

I'm using a PHP class someone wrote to interface with the BaseCamp API.
The particular call I'm doing is to retrieve the items in a todo list, which works fine.
My problem is, I'm not sure how to access just the todo-items property of the object that is returned. Here's the var_dump of the returned object:
object(stdClass)[6]
public 'completed-count' => string '0' (length=1)
public 'description' => string 'Description String' (length=89)
public 'id' => string '12345' (length=7)
public 'milestone-id' => string '' (length=0)
public 'name' => string 'Error Reports' (length=13)
public 'position' => string '1' (length=1)
public 'private' => string 'false' (length=5)
public 'project-id' => string '58904' (length=7)
public 'tracked' => string 'false' (length=5)
public 'uncompleted-count' => string '1' (length=1)
public 'todo-items' =>
object(stdClass)[3]
public 'todo-item' =>
object(stdClass)[5]
public 'completed' => string 'false' (length=5)
public 'content' => string 'content string here' (length=133)
public 'created-on' => string '2009-04-16T20:33:31Z' (length=20)
public 'creator-id' => string '23423' (length=7)
public 'id' => string '234' (length=8)
public 'position' => string '1' (length=1)
public 'responsible-party-id' => string '2844499' (length=7)
public 'responsible-party-type' => string 'Person' (length=6)
public 'todo-list-id' => string '234234' (length=7)
public 'complete' => string 'false' (length=5)
How can I access the todo-items portion of this object?
<?php
$x = new StdClass();
$x->{'todo-list'} = 'fred';
var_dump($x);
So, $object->{'todo-list'} is the sub-object. If you can set it like that, then you can also read it the same way:
echo $x->{'todo-list'};
Another possibility:
$todolist = 'todo-list';
echo $x->$todolist;
If you wanted to convert it to an array, which can be a little more easily (ie the obvious $ret['todo-list'] accessing), this code is taken almost verbatim from Zend_Config and will convert for you.
public function toArray()
{
$array = array();
foreach ($this->_data as $key => $value) {
if ($value instanceof StdClass) {
$array[$key] = $value->toArray();
} else {
$array[$key] = $value;
}
}
return $array;
}
Try this simplest way!
$obj = $myobject->{'mydash-value'};
$objToArray = array($obj);

How to avoid errors while parsing through array in PHP?

I am trying to migrate user data from a Drupal database to Wordpress. I'm trying to parse through a data column from Drupal and reorganize it so I can import it where I need to in the Wordpress database. The data column in Drupal is a serialized string:
a:12:{s:23:"profile_membership_type";s:4:"Full";s:21:"ms_membership_add_new";s:0:"";s:18:"ms_membership_mpid";s:0:"";s:25:"ms_membership_amount_paid";s:0:"";s:32:"ms_membership_transaction_number";s:0:"";s:30:"ms_membership_current_payments";i:1;s:26:"ms_membership_max_payments";s:0:"";s:24:"ms_membership_start_date";a:3:{s:4:"year";s:4:"2014";s:5:"month";s:1:"2";s:3:"day";s:2:"13";}s:27:"ms_membership_should_expire";b:0;s:24:"ms_membership_expiration";a:3:{s:4:"year";s:4:"2014";s:5:"month";s:1:"2";s:3:"day";s:2:"13";}s:20:"ms_membership_status";i:3;s:7:"contact";i:1;}
I keep getting this error:
Warning: Invalid argument supplied for foreach()
This is my code thus far:
$fixed = preg_replace_callback(
'/s:([0-9]+):\"(.*?)\";/',
function ($matches) { return "s:".strlen($matches[2]).':"'.$matches[2].'";'; },
$data
);
$original_array = unserialize($fixed);
foreach ($original_array as $key => $value) {
echo $value['profile_membership_type'];
};
check with if condition before iteration
if(is_array($original_array) && !empty($original_array)){
foreach ($original_array as $key => $value) {
echo $value['profile_membership_type'];
}
}
Just cast to an array.
foreach ( (array) $original_array as $key => $value) {
echo $value['profile_membership_type'];
}
You can easily check to see if the variable you're iterating through is an array;
if(isset($original_array) && is_array($original_array)) {
foreach ( $original_array as $key => $value) {
echo $value['profile_membership_type'];
}
}
Edited to include a check to ensure the variable exists.
You have a php serialized string.
I presume the leading f in your question is a typo, as the rest is a valid serialized array:
$array = unserialize('a:12:{s:23:"profile_membership_type";s:4:"Full";s:21:"ms_membership_add_new";s:0:"";s:18:"ms_membership_mpid";s:0:"";s:25:"ms_membership_amount_paid";s:0:"";s:32:"ms_membership_transaction_number";s:0:"";s:30:"ms_membership_current_payments";i:1;s:26:"ms_membership_max_payments";s:0:"";s:24:"ms_membership_start_date";a:3:{s:4:"year";s:4:"2014";s:5:"month";s:1:"2";s:3:"day";s:2:"13";}s:27:"ms_membership_should_expire";b:0;s:24:"ms_membership_expiration";a:3:{s:4:"year";s:4:"2014";s:5:"month";s:1:"2";s:3:"day";s:2:"13";}s:20:"ms_membership_status";i:3;s:7:"contact";i:1;}');
var_dump($array);
/*
array (size=12)
'profile_membership_type' => string 'Full' (length=4)
'ms_membership_add_new' => string '' (length=0)
'ms_membership_mpid' => string '' (length=0)
'ms_membership_amount_paid' => string '' (length=0)
'ms_membership_transaction_number' => string '' (length=0)
'ms_membership_current_payments' => int 1
'ms_membership_max_payments' => string '' (length=0)
'ms_membership_start_date' =>
array (size=3)
'year' => string '2014' (length=4)
'month' => string '2' (length=1)
'day' => string '13' (length=2)
'ms_membership_should_expire' => boolean false
'ms_membership_expiration' =>
array (size=3)
'year' => string '2014' (length=4)
'month' => string '2' (length=1)
'day' => string '13' (length=2)
'ms_membership_status' => int 3
'contact' => int 1
*/
Note that there is only a single profile_membership_type element, so there is no need to loop:
echo $array['profile_membership_type']; // Full

PHP How to test a value of standard class object

I would like to check if the value of a standard class object has a value of 'None'. The object is a PDO and pulls data from the database.
Here is the data from a var_dump:
array (size=1)
0 =>
object(stdClass)[8]
public 'Subid' => string '1' (length=1)
public 'id' => string '27' (length=2)
public 'english' => string 'English Standard' (length=16)
public 'maths' => string 'Mathematics General 2' (length=21)
public 'hsie1' => string 'Modern History' (length=14)
public 'science1' => string 'Biology' (length=7)
public 'science2' => string 'None' (length=4)
public 'science3' => string 'None' (length=4)
public 'tech1' => string 'Agriculture' (length=11)
public 'tech2' => string 'None' (length=4)
public 'extension' => string 'None' (length=4)
public 'arts1' => string 'None' (length=4)
public 'arts2' => string 'Dance' (length=5)
public 'pdhpe1' => string 'None' (length=4)
public 'vet1' => string 'None' (length=4)
public 'start_time' => string '2016-11-15 19:54:08' (length=19)
Is it possible to loop through the keys and test the values?
You can foreach over an array and the public properties of an object
So
foreach ( $array as $obj ) {
foreach ( $obj as $prop => $val ) {
if ( $val == 'None' ) {
echo $prop . ' = ' . $val;
}
}
}
EDIT:
I dont see why you had to change anything here is a quick test I ran
$o = new stdClass;
$o->p1 = 1;
$o->p2 = 'two';
$o->p3 = 'None';
$array = array($o);
var_dump($array);
foreach ( $array as $obj ) {
foreach ( $obj as $prop => $val ) {
if ( $val == 'None' ) {
echo $prop . ' = ' . $val;
}
}
}
And the results were
array(1) {
[0] =>
class stdClass#1 (3) {
public $p1 => int(1)
public $p2 => string(3) "two"
public $p3 => string(4) "None"
}
}
p3 = None

How to convert stdClass object in to refrence array? (PHP)

I have variable $related witch is stdCalss object and i want to convert it with one foreach loop in to reffrence array.
Var_dump of Object $related:
array (size=19)
0 =>
object(stdClass)[20]
public 'id_product' => string '1568' (length=4)
public 'related' => string '1567' (length=4)
1 =>
object(stdClass)[21]
public 'id_product' => string '1568' (length=4)
public 'related' => string '1562' (length=4)
2 =>
object(stdClass)[22]
public 'id_product' => string '1568' (length=4)
public 'related' => string '1564' (length=4)
3 =>
object(stdClass)[23]
public 'id_product' => string '1568' (length=4)
public 'related' => string '1410' (length=4)
4 =>
object(stdClass)[24]
public 'id_product' => string '111' (length=3)
public 'related' => string '77' (length=2)
5 =>
object(stdClass)[25]
public 'id_product' => string '111' (length=3)
public 'related' => string '1610' (length=4)
Php code:
foreach ($related AS $r){
????
}
var_dump($rels);
Wished Output:
$rels = array(
'1568'=>'1567, 1562, 1564, 1410',
'111'=>'77,1610'
);
Build a temporary array and implode it:
foreach($related AS $r) {
$temp[$r->id_product][] = $r->related;
$rels[$r->id_product] = implode(', ', $temp[$r->id_product]);
}
print_r($rels);
$rels = array ();
foreach ($related as $r){
$rels[$r->id_product] .= $r->related . ","; // put all of them with respective key together
}
$rels = array_map(
function ($a) {
$a = preg_replace('~,(?!.*,)~', '', $a);
return $a;
}
,$rels); // remove last commas
var_dump($rels);
Try,
$rels = array();
foreach($related as $r){
$rels[$r->id_product] .= $r->related.', ';
}
array_walk_recursive($related, function(&$item){
$item = rtrim($item,', ');
});
From the PHP docs: http://php.net/manual/en/language.types.type-juggling.php

Categories