I have this code in PHP:
$rules = array(
"s0" => array(
"a" => "s1_s2_s3",
"b" => "s2_s3"
),
"s1_s2" => array(
"a" => "s1_s2",
"b" => "s2_s3"
),
);
And want to print it like this:
s0 -- a --- s1_s2_s3
s0 -- b --- s2_s3
s1_s2 -- a --- s1_s2
s1_s2 -- b --- s2_s3
How do I do it?
This is how you do it:
$rules = array(
"s0" => array(
"a" => "s1_s2_s3",
"b" => "s2_s3"
),
"s1_s2" => array(
"a" => "s1_s2",
"b" => "s2_s3"
),
);
foreach ($rules as $key => $args) {
foreach ($args as $key2 => $vals) {
print $key . ' -- ' . $key2 . ' --- ' . $vals . '<br>';
}
}
To edit the array
You would use array_push
or []
.
array_push($rules, ['another' => ['c' => 'value']]);
$rules['another'] = ['c' => 'value']];
To add or update to the array at an index:
$rules['another']['c'] = 'change c value';
To achieve this you have to traverse the array. To do this, you need a loop, and in PHP, there is a function foreach
. Here is the example-
Given array:
$rules = array("s0" => array("a" => "s1_s2_s3",
"b" => "s2_s3"
),
"s1_s2" => array("a" => "s1_s2",
"b" => "s2_s3"
)
);
foreach ($rules as $key => $value) {
foreach ($value as $sub_key => $sub_val) {
echo "<p>".$key." -- ".$sub_key." --- ".$sub_val."</p>";
}
}
The foreach construct provides an easy way to iterate over arrays.
Output:
s0 -- a --- s1_s2_s3
s0 -- b --- s2_s3
s1_s2 -- a --- s1_s2
s1_s2 -- b --- s2_s3