为数组中的每个值添加另一个参数[关闭]

问题描述:

I have this code,

$values = array('a' => 'aa', 'b' => 'bb', 'c' => 'cc');
foreach ($values as $part1 => $part2) {
    echo $part1;
    echo $part2;
    }

How can I add another parameter to each value in the array, something like this?

$values = array('a' => 'aa' => 'aaa', 'b' => 'bb' => 'bbb', 'c' => 'cc' => 'ccc');
foreach ($values as $part1 => $part2 => $part3) {
    echo $part1; 
    echo $part2;
    echo $part3;
    }

Ty!;)

Not sure exactly what you're trying to do, but I think you're heading in the direction of having subarrays. Here's an example:

$values = array(
    'a' => 
        array( 'aa', 'aaa' ),
    'b' => 
        array( 'bb', 'bbb')
    //etc
);

var_dump($values);

Edit

To output, just have a two stage loop:

foreach($values as $k => $v) {
    echo($k . ':<br>'); // Will output the keys from above
    if(is_array($v)) {
        foreach($v as $i => $j)              // The value is an array, so iterate 
            echo(' &nbsp; ' . $j . '<br>');  // over all sub-elements 

    } else
        echo(' &nbsp; ' . $v . '<br>');
}

That isnt legal in PHP, since what you assign is key => value.

What you actually want is a multidimensional array, as such:

$values = array(
 array('a','aa','aaa'),
 array('b','bb','bbb')
 );

foreach($values as $value) //Loop through all values
{
 foreach($value as $v) //Loop through each individual value 
 {
   echo $v . ' ,' ;
 }
 echo '<br />';
}

To make the structure more clear you can use the print_r function to visualise the array.

echo $part1.$part2;

is what you're looking for?

Although your question is tooooooo vague and I'd prefer to close it instead of answering but here is another guess

$number = 3;
$values = array('a', 'b', 'c');
foreach ($values as $char) {
  for ($i=1;$i<=$number;$i++)
    echo str_repeat($char,$i),"
";
  }
}

for output

<?php

$values = array('a' => 'aa', 'b' => 'bb', 'c' => 'cc');

foreach ($values as $key => $val) {
    echo $key . ' => ' . $val . $key . "
";
}

?>

for assignment

<?php

$values = array('a' => 'aa', 'b' => 'bb', 'c' => 'cc');

foreach ($values as $key => $val) {
    $values[$key] += $key;
}

?>