PHP Multidimensional mixed arrays - php

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
}

Related

Getting comma separated values from PHP array

I have an array thusly
$main_array = [
["image" => "james.jpg", "name" => "james", "tag" => "spacey, wavy"],
["image" => "ned.jpg", "name" => "ned", "tag" => "bright"]
["image" => "helen.jpg", "name" => "helen", "tag" => "wavy, bright"]
]
I use a foreach to echo some HTML based on the value of tag. Something like this
foreach($main_array as $key => $array) {
if ($array['tag'] == "bright") {
echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';
}
}
This only outputs "ned" as matching the tag "bright". But it should output "helen" too. Similarly:
foreach($main_array as $key => $array) {
if ($array['tag'] == "wavy") {
echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';
}
}
Should output "james" and "helen". What kind of function do I need to achieve the desired result?
When checking an item in a list of items, you can use explode() to split it into parts (I've used split by ", " as each item seems to have a space as well) and then use in_array() to check if it is in the list...
if (in_array("bright", explode( ", ", $array['tag']))) {
You cant do it directly, because it return key with values in string. Below are the working code.
<?php
$main_array = [
["image" => "james.jpg", "name" => "james", "tag" => "spacey, wavy"],
["image" => "ned.jpg", "name" => "ned", "tag" => "bright"],
["image" => "helen.jpg", "name" => "helen", "tag" => "wavy, bright"]
];
foreach($main_array as $key => $array) {
$str_arr = explode (", ", $array['tag']);
foreach ($str_arr as $key2 => $array2) {
if ($array2 == "wavy") {
echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';
}
}
}
?>

How to access keys and first string value while traversing a multi-dimensional array?

Desired result: "My preferred salty food is the snack Rufles".
I would like to echo the array "snack" inside the array "salty food" as a string:
$food = array(
"salty food" => array(
"snack" => array(
0 => "Rufles",
1 => "Generic"
)
)
);
echo "My prefered ";
foreach($food as $key => $value) //salty food
echo $key;
echo " is the ";
//--MY DOUBT IS HERE. DESIRED ECHO: "snack" (FROM THE DEEP ARRAY):
foreach($food as $key => $value)
echo $key["snack"];
print_r($food["salty food"]["snack"][0]); //Rufles
Use nested loops:
echo "My preferred ";
foreach ($food as $type1 => $value1) {
echo $type1;
echo " is the ";
foreach ($value1 as $type2 => $value2) {
echo "$type2 $value2[0]";
}
}
DEMO
Should be ok
<?php
$food = array(
"salty food" => array(
"snack" => array(
0 => "Rufles",
1 => "Generic"
)
)
);
echo "My prefered ";
foreach($food as $key1 => $value){
echo $key1;
echo " is the ";
foreach($value as $key2 => $value){
echo $key2." ";
}
}
print_r($food["salty food"]["snack"][0]);
?>

PHP multidimensional array foreach echo value

I'm having a hard time wrapping my head around this one. I have an array with different keys/values, I want to do a loop that allows me to put in different code wrappings. I'm working with an array that I'm trying to get as an XML.
This is an example of what I have..
I have what came with the code commented out and what I'm trying to do just below it in the foreach
// Multidimensional array
$superheroes = array(
"spider-man" => array(
"name" => "Peter Parker",
"email" => "peterparker#mail.com",
),
"super-man" => array(
"name" => "Clark Kent",
"email" => "clarkkent#mail.com",
),
"iron-man" => array(
"name" => "Harry Potter",
"email" => "harrypotter#mail.com",
)
);
// Printing all the keys and values one by one
$keys = array_keys($superheroes);
for($i = 0; $i < count($superheroes); $i++) {
echo $keys[$i] . "{<br>";
foreach($superheroes[$keys[$i]] as $key => $value) {
// echo $key . " : " . $value . "------";
echo '<wp:meta_key>'.$value['email'].'<wp:meta_key>';
echo '<wp:meta_value><![CDATA['.$value['name'].']]></wp:meta_value>';
}
echo "}<br>";
}
This is how you iterate the array, two levels deep:
foreach($superheroes as $key => $hero) {
echo $key."\n";
foreach ($hero as $heroKey => $heroValue) {
echo "\t".$heroKey."=>".$heroValue."\n";
}
}
You will have to adjust it to your output, but im showing the concept. The first foreach iterates all the heroes, and the second foreach iterates all the key/value pairs of each hero
EDIT: Hold on, its a bit unclear what you actually want. Is this what you want?
foreach($superheroes as $key => $hero) {
echo $key."\n";
echo "\t".$hero['email']."\n";
echo "\t".$hero['name']."\n";
}

Convert multidimensional array to a simple array by recursion

How to convert this array:
$array = [
"order" => [
"items" => [
"6" => [
"ndc" => "This value should not be blank."
],
"7" => [
"ndc" => "This value should not be blank."
]
]
]
];
to
$array = [
"order[items][6][ndc]" => "This value should not be blank.",
"order[items][7][ndc]" => "This value should not be blank.",
];
First array may have unlimited number of nested levels. So nested foreach is not an option.
I spent a lot of time searching for the solution and got nothing. Can, please, someone help or guide me?
Something like this should do the job :
$newArr = [];
function reduce_multi_arr($array, &$newArr, $keys = '') {
if (!is_array($array)) {
$newArr[$keys] = $array;
} else {
foreach ($array as $key => $val) {
if ($keys === '') $nextKey = $key; // first key
else $nextKey = '[' . $key . ']'; // next [keys]
reduce_multi_arr($val, $newArr, $keys . $nextKey);
}
}
}
reduce_multi_arr($array, $newArr);
print_r($newArr);
Output :
Array
(
[order[items][6][ndc]] => 'This value should not be blank.'
[order[items][7][ndc]] => 'This value should not be blank.'
)

PHP array keys values

I have an array like this
$data = array(
"some" => "163",
"rand" => "630",
"om" => "43",
"words" => "924",
"as" => "4",
"keys" => "54"
);
How can I get each set's key associated with their values like this:
foreach ($data as $stuff){
$this->$stuff["key"] = $stuff["value"];
}
foreach ($data as $key => $value){
echo "$key => $value\n";
}
foreach($data as $key => $value)
{
// $key and $value variable are available here
// First iteration values would be: $key = "some" and $value = "163"
}

Categories