Rajasekaran Raji
Rajasekaran Raji

Reputation: 74

How to Convert Nested array to Value in PHP?

My arrays

a:3:{s:6:"Choice";a:2:{i:0;s:5:"First";i:1;s:6:"Second";}s:5:"fcode";s:26:"form_rajas_exmsw2rpc81anlj";s:9:"useremail";s:26:"[email protected]";}

array (
  'Choice' => 
  array (
    0 => 'First',
    1 => 'Second',
  ),
  'fcode' => 'form_rajas_exmsw2rpc81anlj',
  'useremail' => '[email protected]',
)

my php code

$arrays = 'a:3:{s:6:"Choice";a:2:{i:0;s:5:"First";i:1;s:6:"Second";}s:5:"fcode";s:26:"form_rajas_exmsw2rpc81anlj";s:9:"useremail";s:26:"[email protected]";}';

$decode = unserialize($arrays);
foreach($decode as $key => $value) {
    echo '<td width="100">' . $value . '</td>';
}

My Error is :

Notice: Array to string conversion in....

The first Values in Nested Array.

How to convert nested array as a Value?

I need to show like this,

<tr><td>First,Second</td><td>form_rajas_exmsw2rpc81anlj</td><td>[email protected]</td></tr>

Upvotes: 0

Views: 114

Answers (2)

Barmar
Barmar

Reputation: 781096

If $value is an array, you need a nested loop.

foreach ($decode as $key => $value) {
    if (!is_array($value)) {
        $value = array($valule);
    }
    foreach ($value as $subvalue) {
        echo "<td width='100'>$subvalue</td>";
    }
}

If you can have multiple levels of nesting, you should write a recursive function that handles each level.

If you want a sub-array to be shown as a comma-separated list, you can use implode.

foreach ($decode as $key => $value) {
    if (is_array($value)) {
        $value = implode(', ', $value);
    }
    echo "<td width='100'>$subvalue</td>";
}

Upvotes: 1

Jayo2k
Jayo2k

Reputation: 249

you have nested array populated with elements of diferent size so you will always get an error. so in your foreach loop, you can check if the value is an array or not, like for instance

if (count($value)>1){
//code here like for instance echo $value[0]...
}//not recomended becuse an array can have only one value, but you can if you know you will put at least 2

or

if(is_array($value)..

Me I will do the following:

foreach($thing as $thingy =>$that){
   //check if array or not
   if(is_array($that)){
       foreach($that as $t)
             //do whatever
   }else
      //do whatever
}

Upvotes: 0

Related Questions