繁体   English   中英

无法将字符串偏移量用作数组

[英]Cannot use string offset as an array

嗨,我有一个看起来像这样的数组

Array
(
        [0] => Array
                (
                        [Marque] => AUDI
                        [Famille] => A4 Avant N1
                )
        [1] => Array
                (
                        [Marque] => AUDI
                        [Famille] => A3
                )
        [2] => Array
                (
                        [Marque] => AUDI
                        [Famille] => A5
                )
        [3] => Array
                (
                        [Marque] => AUDI
                        [Famille] => A4
                )
)

我需要一个看起来像这样的数组:

引用

Array
(
    [AUDI] => Array
    (
        [0] => A4 Avant N1
        [1] => A3
        [2] => A5
        [3] => A4
    )

)

如此票价我就知道了:

if (isset($_GET['debug'])){ $stri=array(); $i=0; foreach($csv_array as $car){
    if ( !in_array("$car[Marque]", $stri) ) {
    $stri[] = "$car[Marque]";
    }
    if ( !in_array("$car[Famille]", $stri) ) {
    $stri[$i][$car[Marque]][] = "$car[Famille]";
    }     $i++; }

echo "<pre>"; print_r($stri); echo "</pre>";

但这给了我

致命错误:无法将字符串偏移量用作数组

尝试在数组键周围加上引号:

if (isset($_GET['debug'])){ $stri=array(); $i=0; foreach($csv_array as $car){
    if ( !in_array("$car['Marque']", $stri) ) {
    $stri[] = "$car['Marque']";
    }
    if ( !in_array("$car['Famille']", $stri) ) {
    $stri[$i][$car['Marque']][] = "$car['Famille']";
    }     $i++; }

echo "<pre>"; print_r($stri); echo "</pre>";

您必须使用单引号正确地提取值:

$car[Famille] => $car['Famille']

[编辑]现在我明白了...

$stri = Array();

foreach($csv_array as $car)
{
    if (!array_key_exists("$car['Marque']", $stri))
    {
        $stri["$car['Marque']"] = Array();
        $stri["$car['Marque']"][] = "$car['Famille']";
    else
        $stri["$car['Marque']"][] = "$car['Famille']";
}

var_dump($stri);

暂无
暂无

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

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