注意:C:\xampp\htdocs\example\echo.php 中第 8 行数组到字符串的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34208064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:50:44  来源:igfitidea点击:

Notice: Array to string conversion in C:\xampp\htdocs\example\echo.php on line 8 Array

phparraysmultidimensional-array

提问by Nishant Dixit

<?php
    $products = array();    
    $products[101] = array(
        "name" => "Logo Shirt, Red",
        "price" => 18,
        "img" => "img/shirts/shirts-101.jpg"
);
    echo $products;
?>

I am trying to run this php file and it keeps giving me this error - Notice: Array to string conversion in C:\xampp\htdocs\example\echo.php on line 8 Array.

我正在尝试运行这个 php 文件,它一直给我这个错误 - 注意:数组到字符串转换在 C:\xampp\htdocs\example\echo.php 中的第 8 行数组。

All i want to do is echo out each and every element inside the array. I've also tried

我想要做的就是回显数组中的每个元素。我也试过

<?php
    $products = array();    
    $products[101] = array(
        "name" => "Logo Shirt, Red",
        "price" => 18,
        "img" => "img/shirts/shirts-101.jpg"
    );
    foreach($products as $product){
        echo $product;
    }
?>

EDIT1: okay guys what if there are multiple similar arrays like $product[101] $product[102] $product[103] $product[104] . . . $product[n]

EDIT1:好吧,如果有多个类似的数组,比如 $product[101] $product[102] $product[103] $product[104] 怎么办。. . $产品[n]

What then?

然后怎样呢?

回答by Ben

If you echoan array, it will either give you an error or just output "Array".

如果你echo是一个数组,它要么给你一个错误,要么只输出“数组”。

In your second example, $products[101]is alsoan array.

在第二个例子中,$products[101]阵列。

So you can do this:

所以你可以这样做:

foreach($products as $product){
    foreach($product as $key => $val){
        echo "$key: $val";
    }
}

Or use print_rto output the data in an array:

或用于print_r输出数组中的数据:

foreach($products as $product){
    print_r($product);
}

回答by Oliver Weitman

if you want to print the $products[101] just do the foreach but do

如果你想打印 $products[101] 只是做 foreach 但做

$products[101] as $product

instead

反而

回答by Johnson Ogwuru

simply just use:

只需使用:

print_r($products)or

print_r($products)或者

var_dump($products)

var_dump($products)

That should do it for you...cheers

那应该为你做...干杯

回答by user2770352

print_r ($products); Use print_r method to print arrays.

打印_r($产品);使用 print_r 方法打印数组。