Shtefko
Shtefko

Reputation: 5

Warning: Illegal string offset PHP 7 foreach

Using php curl. I'm getting an array of data. From which I want to get the following data

if(is_array($jsonRes['prod']['ret']['ProdIt'])){
    foreach($jsonRes['prod']['ret']['ProdIt'] as $obRes){
        $arP["ARTI"] = $obRes['Article'];
        $arP["ALT"] = $obRes['Name'];
        $arP["BR"] = $obRes['Brand'];

I'm getting an error:

Warning: Illegal string offset 'Article' in /........php on line 48

Warning: Illegal string offset 'Name' in /...........php on line 49

Warning: Illegal string offset 'Brand' in /...........php on line 50

Here is an array

Array
(
    [ret] => Array
        (
            [ProductsItemCount] => 1
            [ProdIt] => Array
                (
                    [Code] => 0789087
                    [Article] => 3011317
                    [Name] => Price cash
                    [Brand] => HATTAT
                    [Price] => 0
                    [Currency] => EUR
                    [Stock] => Array
                        (
                            [StockItem] => Array

The error does not always occur. When an array looks like this, then it has no errors

Array
(
    [ret] => Array
        (
            [ProductsItemCount] => 2
            [ProdIt] => Array
                (
                    [0] => Array
                        (
                            [Code] => 908877677
                            [Article] => 8200892104
                            [Name] => Tovare
                            [Brand] => RENAULT
                            [Price] => 0
                            [Currency] => EUR
                            [Stock] => Array

Upvotes: 0

Views: 3507

Answers (1)

Barmar
Barmar

Reputation: 781098

You need to check whether ProdIt is 1-dimensional or 2-dimensional. In the first example, it's a single associative array, not an array of associative arrays.

$prodit = $jsonRes['prod']['ret']['ProdIt'];
if (is_array($prodit)) {
    if (isset($prodit['Article'])) { // 1-dimensional, turn into 2-dimensional
        $prodit = array($prodit);
    }
    foreach ($prodit as $obRes) {
        ...
    }
}

Upvotes: 1

Related Questions