Scooter Daraf
Scooter Daraf

Reputation: 535

Loop through 3 elements in array

i can loop through 2 elements in an array , but here im having trouble looping through 3 elements .

this is my example :

   $y = array('cod=>102,subcod=>10201,name=>"blabla"',
              'cod=>103,subcod=>10202,name=>"blibli"',
              'cod=>103,subcod=>10202,name=>"bblubl"')

my desire result is how to get the value of cod and subcod and name of every line .

I tried this :

     foreach ($y as $v) {
                echo $v['cod'] ;
                echo $v['subcod'];
                echo $v['name'] ;
             }

but didnt work , im getting this error : Warning: Illegal string offset 'cod' and same error for every offset .

any help would be much apreciated.

Upvotes: 1

Views: 50

Answers (1)

thecodeparadox
thecodeparadox

Reputation: 87073

If you can't change you're array

Then you need to format that and then use the loop and get the value.

function format_my_array($arg) {
    $new = array();

    foreach( $arg as $n => $v ) {

        // splitting string like 
        // 'cod=>102,subcod=>10201,name=>"blabla"'
        // by comma 
        $parts = explode(',', $v);

        $new[$n] = array();
        foreach( $parts as $p ) {

            // splittin again by '=>' to get key/value pair
            $p = explode('=>', trim($p));
            $new[$n][$p[0]] = $p[1];
        }
    }

    return $new;
}

$new_y = format_my_array($y);

foreach( $new_y as $v ) {
    echo $v['cod'];
    echo $v['subcod'];
    echo $v['name'];
}

Upvotes: 2

Related Questions