Asked  7 Months ago    Answers:  5   Viewed   44 times

print_r($samplearr) prints the following for my array containing 3 items:

Array ( [4722] => Array ( [value1] => 52 [value2] => 46 )
Array ( [4922] => Array ( [value1] => 22 [value2] => 47 )
Array ( [7522] => Array ( [value1] => 47 [value2] => 85 )

I want to put these into an HTML table so I was doing a foreach but its not doing what I expected:

foreach($samplearr as $item){
     print "<tr><td>" . key($item) . "</td><td>" . $samplearr['value1'] . "</td><td>" . $samplearr['value2'] . "</td></tr>";
}

Which is returning:

<tr><td>value1</td><td>52</td><td>46</td></tr>

This would be the first output I am wanting:

<tr><td>4722</td><td>52</td><td>46</td></tr>

What function do I need to be using instead of key($item) to get the 4722?

 Answers

62

Try this:

foreach($samplearr as $key => $item){
  print "<tr><td>" 
      . $key 
      . "</td><td>"  
      . $item['value1'] 
      . "</td><td>" 
      . $item['value2'] 
      . "</td></tr>";
}
Wednesday, March 31, 2021
 
Gordnfreeman
answered 7 Months ago
48

That's invalid syntax. You'd have to build the "parent" portions of the array first. THEN add in the sub-array stuff with the foreach loop:

$foo = array(
    'label' => 'Assign to user',
    'desc' => 'Choose a user',
    'id' => $prefix.'client',
    'type' => 'radio',
    'options' => array()
);

foreach ($clients as $user) {
    $foo['options'][] = array (  
        'label' => $user->user_login,  
        'value' => $user->user_login,
    );
}
Wednesday, March 31, 2021
 
mopsyd
answered 7 Months ago
52

You need to iterate the elements from the inside array, like this:

foreach($resultArray as $row => $innerArray){
  foreach($innerArray as $innerRow => $value){
    echo $value . "<br/>";
  }
}
Wednesday, August 4, 2021
 
Cam1989
answered 3 Months ago
87

unset it first in case it is already in the proper format, otherwise you will remove what you just defined:

foreach($array as $key => $value)
    {
        unset($array[$key]);
        $array[ucfirst($key)] = $value;
    }
Thursday, August 5, 2021
 
JackTheKnife
answered 3 Months ago
68
$c = array_count_values($stuff); 
$val = array_search(max($c), $c);
Saturday, September 18, 2021
 
ttran4040
answered 1 Month ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :