I'm kinda stucked here.
I'm trying to build URL for product variants like:
&brand=6&color=11,12,etc
So how can I combine the keys of array into one string like above
Also If you could suggest me another way to achieve the desired result.
Thank you very much!
You first have to combine the values of "brand" with the values of "color". Afterwards, you can output them together:
<?php
$columns = [
'brand' => [
['b1A', 'b1B'],
['b2A', 'b2B'],
],
'color' => [
['c1A', 'c1B'],
['c2A', 'c2B'],
],
];
$data = [];
foreach ($columns as $title => $rows) {
foreach ($rows as $id => $values) {
if (!isset($data[$id])) {
$data[$id] = [];
}
$data[$id][$title] = $values;
}
}
foreach ($data as $row) {
$output = '';
foreach ($row as $key => $values) {
$output .= '&' . $key . '=' . implode(',', $values);
}
echo $output . '<br/>' . PHP_EOL;
}
<?php
$filters = [
"brand" => [
1 => "Adidas",
2 => "Puma"
],
"color" => [
1 => "White",
2 => "Blue",
3 => "Red",
4 => "Yellow"
]
];
foreach($filters['brand'] as $key => $val){
foreach($filters['color'] as $k => $v){
echo "brand=$key,$val&color=$k,$v" . PHP_EOL;
echo "brand=$val&color=$v" . PHP_EOL;
}
}
Output
brand=1,Adidas&color=1,White
brand=Adidas&color=White
...
Example 2;
foreach($filters['brand'] as $key => $val){
echo "&brand=$key,$val&color=" . implode(',',$filters['color']) . PHP_EOL;
}
&brand=1,Adidas&color=White,Blue,Red,Yellow
&brand=2,Puma&color=White,Blue,Red,Yellow
Related
<?php
$arr =
[
'name' => 'hussin' ,
"age" => 25,
'job' =>
[
'php', 'ajax'
]
];
foreach ($arr as $key => $value)
{
if(!is_array($arr[$key]))
echo $key .' '. $value."<br>";
else
foreach ($arr['job'] as $key => $value)
echo $key .' '. $value."<br>";
}
?>
result
name Hussien
age 27
0 php
1 ajax
Is there a better solution than this to print the results?
I have an associative array with regular data, including a array type, which is the best solution for accessing all data
I may be misunderstanding, but I think you're looking for a recursive algorithm:
function printAll(array $arr){
foreach($arr as $k => $v){
if(is_array($v)){
return printAll($v);
}
print $k . ":" . $v . "\r\n";
}
}
printAll(['name' => 'hussin' ,"age" => 25,'job' => ['php', 'ajax']]); // name:hussin age:25 0:php 1:ajax
Now, this can of course be improved to deal with other iterables and the nested array keys, but hopefully you get the jist.
How Do I access the innermost array? the grade is giving me a Notice: Array to string conversion in /scripts/array.php on line 34
grade: Array
$data = array();
$data[0] = 78;
$data[1] = 34;
$data[2] = 87;
$student = array(0 => array(
"Stdno" => "212",
"name" => "Lorem Ipsum",
"subject" => "Networking",
"grade" => $data
),
1 => array(
"Stdno" => "212",
"name" => "Jimmy Shu",
"subject" => "Informatics",
"grade" => $data
),
2 => array(
"Stdno" => "212",
"name" => "Amet Dolor",
"subject" => "Discrete Combinatorics",
"grade" => $data
)
);
foreach ($student as $key => $value) {
foreach ($value as $key => $value) {
echo "<b>{$key}</b>: {$value}";
echo "<br />";
}
echo "<br />";
}
First of all, you should really not use $key and $value again (in fact, I thought foreach ($value as $key=>$value) didn't work).
Assuming you want to echo the $data element at the same position than in your $student array (i.e. echo $data[0] for $student[0]), you should use the first key :
foreach ($student as $key => $value) {
foreach ($value as $key2 => $value2) {
echo "<b>{$key2}</b>: ";
if ($key2 == 'grade')
echo $value2[$key];
else
echo $value2;
echo "<br />";
}
echo "<br />";
}
First, just a comment please avoid using same keys on foreach. like in your $value.
To fix your issue, it clearly says, it's an array but you try to echo it, you could try to use this instead.
echo "<b>{$key}</b>: " . json_encode($value);
As stated by #roberto06 you should avoid using same variables for cycles that are nested. Those variables will be overwriten by new values.
To the question:
You could check wether $value is string or array
is_array($val) || is_string($val)
based on result you could write another foreach cycle or print string.
in your second foreach you are foreaching this array:
array(
"Stdno" => "212",
"name" => "Lorem Ipsum",
"subject" => "Networking",
"grade" => $data
)
so the (second) $key will be "Stdno", "name", "subject", "grade"
and values will be "212", "Lorem Ipsum", "Networking" (those are strings) and $data (this is array)
to print this array, you need to create new foreach and use it only when $key == "grade" or use implode on it:
if($key == "grade"){
$i = implode(', ', $value);
//print or something
}
I want to foreach the game name and info and each game must filter as platform_name.
$list = (object)[];
$list->egame =
[
(object)['platform_name'=>'TT', 'game'=>(object)[(object)['game_name'=>'game1', 'info'=>'test1'],(object)['game_name'=>'game2', 'info'=>'test2'],(object)['game_name'=>'game3', 'info'=>'test3']]],
(object)['platform_name'=>'TG', 'game'=>(object)[(object)['game_name'=>'game4', 'info'=>'test4'],(object)['game_name'=>'game5', 'info'=>'test5']]],
(object)['platform_name'=>'TBIN', 'game'=>(object)[(object)['game_name'=>'game6', 'info'=>'test6']]]
];
?>
Try this
$list = (object)[];
$list->egame =
[
(object)['platform_name' => 'TT', 'game' => (object)[(object)['game_name' => 'game1', 'info' => 'test1'], (object)['game_name' => 'game2', 'info' => 'test2'], (object)['game_name' => 'game3', 'info' => 'test3']]],
(object)['platform_name' => 'TG', 'game' => (object)[(object)['game_name' => 'game4', 'info' => 'test4'], (object)['game_name' => 'game5', 'info' => 'test5']]],
(object)['platform_name' => 'TBIN', 'game' => (object)[(object)['game_name' => 'game6', 'info' => 'test6']]]
];
$arr = (array)$list->egame;
for ($i = 0; $i < count($arr); $i++) {
foreach ($arr[$i] as $key => $value) {
$aa = (array)$arr[$i]->game;
foreach ($aa as $k => $v) {
echo $aa[$k]->game_name." ".$aa[$k]->info."<br/>";
}
echo "<br/>";
}
}
Here You go:
<?php
$list = (object)[];
$list->egame =
[
(object)['platform_name'=>'TT', 'game'=>(object)[(object)['game_name'=>'game1', 'info'=>'test1'],(object)['game_name'=>'game2', 'info'=>'test2'],(object)['game_name'=>'game3', 'info'=>'test3']]],
(object)['platform_name'=>'TG', 'game'=>(object)[(object)['game_name'=>'game4', 'info'=>'test4'],(object)['game_name'=>'game5', 'info'=>'test5']]],
(object)['platform_name'=>'TBIN', 'game'=>(object)[(object)['game_name'=>'game6', 'info'=>'test6']]]
];
foreach ( $list->egame as $eg ) {
foreach ( $eg->game as $game ) {
echo "game: " . $game->game_name . " info: " . $game->info . "<br>";
}
}
?>
Edit #1
Includes platform:
foreach ( $list->egame as $eg ) {
foreach ( $eg->game as $game ) {
echo "platform: " . $eg->platform_name . " game: " . $game->game_name . " info: " . $game->info . "<br>";
}
}
i want to send more than on array in foreach() .
i know this way is false .whats the true method ?
$Fname = [1,2,3,4,5];
$Lname = [1,2,3,4,5];
$Addrs = [1,2,3,4,5];
$Mobile = [1,2,3,4,5];
$fields = array(
'name' => 'a',
'type' => 'b',
'value' => 'n',
'show' => 'd',
);
foreach($fields as $key => $n)
{
echo " {$Fname[$key]} , {$Lname[$key]},{$Addrs[$key]} , {$Mobile[$key]},{$key} ,{$n} <br>";
}
If all your arrays have the same number of rows, you can use a for loop instead of a foreach, in conjunction with next() and current() for associative array:
for( $i = 0; $i < count($Fname); $i++ )
{
echo $Fname[$i] . PHP_EOL;
echo $Lname[$i] . PHP_EOL;
echo $Addrs[$i] . PHP_EOL;
echo $Mobile[$i] . PHP_EOL;
echo current($fields) . PHP_EOL;
next($fields);
}
The problem is that your arrays haven't same rows number...
So you have to add some condition like this:
for( $i = 0; $i < count($Fname); $i++ )
{
echo $Fname[$i] . PHP_EOL;
echo $Lname[$i] . PHP_EOL;
echo $Addrs[$i] . PHP_EOL;
echo $Mobile[$i] . PHP_EOL;
if( isset(current($fields)) )
{
echo current($fields) . PHP_EOL;
next($fields);
}
}
i know this way is false...? What's false about it?
foreach() will iterate over an array, not over multiple arrays.... if you absolutely need to iterate over multiple arrays within the same foreach() loop, you can use SPL's MultipleIterator, but it adds a lot more complexity to your code, and the approach that you've taken is as good as any
Just make sure that your keys match up in all the arrays; if they don't then you will have problems
foreach(array_values($fields) as $key => $n)
{
$k = array_keys($fields)[$key];
echo " {$Fname[$key]} , {$Lname[$key]},{$Addrs[$key]} , {$Mobile[$key]},{$k} ,{$n} <br>";
}
Instead of storing your data like that, it'd be easier to store it in an array of associative arrays:
$people = array(
array(
'firstName' => 'Bruce',
'lastName' => 'Wayne',
'address' => '123 East St. Gotham City, XX USA'
'mobile' => '847-847-8475'
),
array(
'firstName' => 'Roland',
'lastName' => 'Deschain',
'address' => 'N/A'
'mobile' => '191-919-1919'
)
);
foreach($people as $person){
echo $person['firstName'] + ', ' + $person['lastName'];
echo $person['address'] + ', ' + $person['mobile'];
}
It's just a cleaner way to store/access your data, makes it easy to use one foreach as well.
Try this code
$arr1 = array("a" => 1, "b" => 2, "c" => 3);
$arr2 = array("x" => 4, "y" => 5, "z" => 6);
foreach ($arr1 as $key => &$val) {}
foreach ($arr2 as $key => $val) {}
var_dump($arr1);
var_dump($arr2);
I need to read nested arrays without knowing how the array will look.
For example;
$data = array(
'Data1_lvl1' => array(
'Data1_lvl2' => "value",
'Data2_lvl2' => array(
'Data1_lvl3' => "value"
)
),
'Data2_lvl1' => 'value'
);
Needs to be formatted to strings like:
Data1_lvl1/Data1_lvl2/
Data1_lvl1/Data2_lvl2/Data1_lvl3/
Data2_lvl1/
But the array can be of any size with any number of nested arrays inside it.
$data = array(
'Data1_lvl1' => array(
'Data1_lvl2' => "value",
'Data2_lvl2' => array(
'Data1_lvl3' => "value"
)
),
'Data2_lvl1' => 'value'
);
function printArray($array)
{
foreach ($array as $key=>$value)
{
echo $key.'/';
if (is_array($value))
{
printArray($value);
} else {
echo '<br>';
}
}
}
printArray($data);
If you want to output only the name of array elements then this recursive function will do the trick.
Your data:
$data = array(
'Data1_lvl1' => array(
'Data1_lvl2' => "value",
'Data2_lvl2' => array(
'Data1_lvl3' => "value"
)
),
'Data2_lvl1' => 'value'
);
Function:
function array2str($array, $str) {
foreach($array as $key => $val) {
if (is_array($val) ) {
$str .= $key . '/';
array2str($val, $str);
}
}
echo $str.'<br />';
return $str;
}
array2str($data);
As you can see the script does ECHO in itself with <br /> to break the line when viewing results in a browser.
One way would to walk recursively through array with function similar to this:
<?php
function f($d, $str = '') {
foreach ($d as $key => $val) {
if (is_array($val)) f($val, $str . '/' . $key); // If this element is array parse next level
else print_r($str . '/' . $key . '/'); // Output current string or do what you need to do with it..
}
}
$data = array(
'Data1_lvl1' => array(
'Data1_lvl2' => "value",
'Data2_lvl2' => array(
'Data1_lvl3' => "value"
)
),
'Data2_lvl1' => 'value'
);
f($data);
with that function:
<?php
function print_tree ($data, $prefix = '', &$index = 1) {
foreach($data as $key => $datum) {
echo $index++ . '. ' . ($new_prefix = $prefix . $key . '/') . PHP_EOL;
if (is_array($datum)) {
print_tree ($datum, $new_prefix, $index);
}
}
}
I get
Data1_lvl1/
Data1_lvl1/Data1_lvl2/
Data1_lvl1/Data2_lvl2/
Data1_lvl1/Data2_lvl2/Data1_lvl3/
Data2_lvl1/