如何在PHP中获取特定的数组值

7
我希望能够在PHP中从数组中输出特定的值。
以下是我的代码,数组为$content
<?php
$content = $_POST;

for($i=1; $i < $content['itemCount'] + 1; $i++) {
  $name = 'item_name_'.$i;
  $quantity = 'item_quantity_'.$i;
  $price = 'item_price_'.$i;
  $image='item_image_'.$i;
  $option='item_options_'.$i;
  $total = $content[$quantity]*$content[$price];
}
?>

<?php
print_r( $content );

?>

输出如下:

Array ( [currency] => INR 
[shipping] => 0 
[tax] => 0 
[taxRate] => 0 
[itemCount] => 3 
[item_name_1] => Our Nest 
[item_quantity_1] => 1 
[item_price_1] => 1900 
[item_options_1] => image: CF01108.jpg, productcode: 602793420 
[item_name_2] => Our Nest 
[item_quantity_2] => 1 
[item_price_2] => 2100 
[item_options_2] => image: CF01110.jpg, productcode: 123870196 
[item_name_3] => Our Nest 
[item_quantity_3] => 1 
[item_price_3] => 1800 
[item_options_3] => image: CF01106.jpg, productcode: 416267436 )

如何在php变量中获取productcode值并将其输出?

示例:

602793420, 123870196, 416267436


你想要这个数组中的所有产品代码吗?你期望的输出是什么? - Aniruddha Chakraborty
在你的for循环中尝试使用以下代码:echo substr($content[$option], strpos($content[$option], 'productcode:')+strlen('productcode:')); - Chetan Ameta
item_options_1的数据类型是什么? - bIgBoY
PHP 语言提供了丰富的函数来进行字符串操作 - axiac
2个回答

4

您可以使用explode()函数获取productcode,例如:

$product_code = explode("productcode: ", $option)[1];

这是参考资料: 所以你的代码应该像这样:
<?php
    $content = $_POST;

    for($i=1; $i < $content['itemCount'] + 1; $i++) {
      $name = 'item_name_'.$i;
      $quantity = 'item_quantity_'.$i;
      $price = 'item_price_'.$i;
      $image='item_image_'.$i;
      $option='item_options_'.$i;
      $product_code = explode("productcode: ", $option)[1];
      $total = $content[$quantity]*$content[$price];
    }
?>

我没有完全得到我想要的,但是explode()帮了我。谢谢。我得到了我的答案 $product_code = explode(", ", $content[$option]); 完成了工作。 - Asesha George
@AseshaGeorge 很高兴能帮到你。 :) - Rajdeep Paul

0
我建议这样做,以防将来该选项可能会有更多的值。
$option = "image: CF01110.jpg, productcode: 123870196";
$options = explode(",", $option);
echo $product_code = explode("productcode: ", $options[1])[1];

谢谢 Amit


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接