简体   繁体   English

PHP使用通配符从数组打印多个值

[英]PHP Print Multiple Values From An Array With A Wildcard

I am trying to print multiple values, through PHP, from an array that includes a wildcard. 我试图通过PHP从包含通配符的数组中打印多个值。 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): 我正在工作(12271 stdClass Object是通配符,第一个stdClass对象是$ order):

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

So the code below works and prints out, correctly, 'MODEL1 1x' 所以下面的代码可以正确地打印出'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' 'MODEL1 1x'和'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 作为参考,我试图从Drupal 7中的Ubercart订单打印出值。谢谢

Just loop all objects. 只需循环所有对象。 I just keep everything as objects (instead of casting to array) for simplicity since there is no need for current() : 为了简单起见,我只是将所有内容保存为对象(而不是转换为数组),因为不需要current()

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

If you ever need the key such as 12271 then: 如果您需要12271这样的密钥,那么:

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

Maybe more readable: 也许更具可读性:

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

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM