PHP Print Multiple Values From An Array With A Wildcard

1.8k views Asked by At

I am trying to print multiple values, through PHP, from an array that includes a wildcard. I have managed to work out the wildcard element from another question on here, but I am now struggling to print multiple vales from multiple entities. I'm working from (12271 stdClass Object is the wildcard and the first stdClass Object is $order):

stdClass Object
(
  [products]
    (
      [12271] => stdClass Object
        (
          [model] => MODEL1
          [qty] => 1
        )

So the code below works and prints out, correctly, 'MODEL1 1x'

<?php
$model = current((array)$order->products)->model;
$qty = current((array)$order->products)->qty;
print $model.' '.$qty.'x';
?>

However, if multiple objects are present, such as

stdClass Object
(
  [products]
    (
      [12271] => stdClass Object
        (
          [model] => MODEL1
          [qty] => 1
        )
      [45897] => stdClass Object
        (
          [model] => MODEL2
          [qty] => 2

I don't know how to print multiple objects so that it prints out:

'MODEL1 1x' and 'MODEL2 2x'

Any help would be much appreciated. For reference, I am trying to print out values from an Ubercart order in Drupal 7. Thanks

2

There are 2 answers

1
AbraCadaver On BEST ANSWER

Just loop all objects. I just keep everything as objects (instead of casting to array) for simplicity since there is no need for current():

foreach($order->products as $object) {
    echo $object->model . ' ' . $object->qty . 'x';
}

If you ever need the key such as 12271 then:

foreach($order->products as $key => $object) {
    echo $key;
    echo $object->model . ' ' . $object->qty . 'x';
}

Maybe more readable:

echo "{$object->model} {$object->qty}x";
0
MifReal On

If order of fields is permanent, you can use this

foreach ($order->products as $product) {
    vprintf('%s %ux' . PHP_EOL, $product);
}

else

foreach ($order->products as $p) {
    printf('%s %ux%s', $p->model, $p->qty, PHP_EOL);
}