Boby
Boby

Reputation: 1202

variable as key multidimensional array

I have this array $data['lists']

Array
(
    [0] => stdClass Object
        (
            [NIK] => 00001
            [NAME] => Name 1
        )

    [1] => stdClass Object
        (
            [NIK] => 00002
            [NAME] => Name 2
        )
)

For some condition the array will be changed so i create a function to get the keys. Here is what i do

foreach($data['lists'] as $key => $val)
   {
        foreach( $val as $keyItem => $valKey)
          {
                $data['column'][] =  $keyItem;
          }
   }   
$data['kolom'] = array_unique($data['column']);

then in HTML I do this

<?php
$no = 0;
for ($y = 0; $y < count($lists); $y++) {
    $no++;
    echo "<tr>";
    echo "<td>" . $no . "</td>";
    for ($x = 0; $x < count($kolom); $x++) {
        echo "<td>" . $lists[$x]->$kolom[$x] . "</td>";
    }
    echo "</tr>";
}

but when i run it, i get this error Message: Array to string conversion. How can i fix it ? thanks in advance

Upvotes: 0

Views: 38

Answers (1)

u_mulder
u_mulder

Reputation: 54831

Why not just:

// iterate over `$lists`
foreach ($lists as $val) {
    $no++;
    echo "<tr>";
    echo "<td>" . $no . "</td>";
    // output every value from each `$lists` item
    foreach ($val as $valKey) {
        echo "<td>" . $valKey . "</td>";
    }
    echo "</tr>";
}

Upvotes: 1

Related Questions