I'm having trouble pulling out the key value pairs in only one sub array of a two dimensional array.
I'm trying to get it in the following format:
"Insect: b: beetle
Insect: m: moth
etc..."
here is what I've got so far:
$animals = array(
'insect' => array('b'=>"beetle", 'm'=>"moth", 's'=>"spider"),
'mammal' => array('d'=>"dolphin", 'h'=>"human", 'c'=>"chimp"),
'fish' => array('a'=>"angler", 'sh'=>"shark", 'p'=>"puffer"));
echo $animals['insect']; // trying to print sub array??
echo "<pre>";
foreach($animals as $Mkey => $domains)
foreach($domains as $key => $species)
echo "$Mkey: $key : $species<br>"; //prints whole array
foreach($animals['insect'] as $Mkey => $species) {
echo "$Mkey : $species<br>";
}
// dynamic key:
$key = 'insect';
foreach($animals[$key] as $Mkey => $species) {
echo "$key: $Mkey : $species<br>";
}
Related
How to get the distinct keys ($key) and multiple different values ($myObjectValues) in list of objects?
My expected outcome is distinct keys displays as column in table and its different values display as multiple rows. The column ($key) should not be hardcore and I plan to display in blade view.
Ideal:
Current Code:
foreach($x as $key => $item) {
print_r($key); //this is list number
foreach($item as $key => $myObjectValues){
print_r($key); //this is my object key
print_r($myObjectValues); //this is my object values
}
}
This is the json array object ($x).
Array(
[0] => stdClass Object
(
[milk_temperature] => 10
[coffeebean_level] => 124.022
)
[1] => stdClass Object
(
[milk_temperature] => 1099
[soya_temperature] => 10
[coffeebean_level] => 99.022
)
[2] => stdClass Object
(
[milk_temperature] => 1099
[coffeebean_level] => 99.022
)
)
You can do it like this, it's not the best approach in the world but it works and you can use it as an example. First you create a list with the table header titles and then start by printing the header and then the values.
<?php
$x = [
(object) [
'milk_temperature' => 10,
'coffeebean_level' => 124.022
],
(object) [
'milk_temperature' => 1099,
'soya_temperature' => 10,
'coffeebean_level' => 99.022
],
(object) [
'milk_temperature' => 1099,
'coffeebean_level' => 99.022
]
];
// list all the keys
$keys = [];
foreach($x as $key => $item) {
$keys = array_merge($keys, array_keys((array) $item));
}
$keys = array_unique($keys);
// echo the header
foreach ($keys as $key) {
echo $key . ' ';
}
echo "\n";
// echo the values
foreach($x as $item) {
foreach ($keys as $key) {
echo $item->$key ?? '-'; // PHP 7+ solution
// echo isset($item->$key) ? $item->$key : '-'; // PHP 5.6+
echo ' ';
}
echo "\n";
}
You can first get the keys of the array with array_keys() and array_collapse():
$columns = array_keys(array_collapse($records));
Then you look through the $records using the same loop you already have. Let's demo it with this example:
$columns = array_keys(array_collapse($records));
foreach($records as $key => $item) {
//these are each record
foreach ($columns as $column) {
//each column where you build the header
// converts $item to an array
$item = (array)$item;
if (! array_key_exists($column, (array)$item)) {
// show '---'
echo '---';
continue;
}
//show $item[$item]
echo $item[$column];
}
}
The great advantage of doing so i.e getting the columns first (apart from converting the stdClass to an array) is that the columns array can be used any way you deem fit.
It would be more beneficial if you can have your data all as array then you can easily use the array functions available on it.
I have an associative array:
$pair = array(
'S'=>'0',
'I'=>'50',
'P'=>'30'
);
From this pair of key and values, I need first occurrence non zero value from key value pair only,
from my example I'm expecting key I and value 50.
Do something like this:
function findNonZero($var){
// returns whether the input is non zero
return($var > 0);
}
$pair = array(
'S'=>'0',
'I'=>'50',
'P'=>'30'
);
$newPair = array_filter($pair, "findNonZero");
var_dump($newPair); //Contains array of non-zero values
You can do that with usual foreach loop
$pair = array(
'S'=>'0',
'I'=>'50',
'P'=>'30'
);
foreach($pair as $k=>$v) {
if ($v) break;
}
echo "$k => $v"; // I => 50
demo
You can use php functions array_filter(), array_slice(), or use a foreach loop.
<?php
// filter out empty values, and get first item
$value = array_slice(array_filter($pair), 0, 1);
// check not empty
if (!empty($value)) {
// get key
echo 'key => '.array_keys($value)[0].PHP_EOL;
// get value
echo 'value => '.array_values($value)[0];
}
https://3v4l.org/tr3bp
Result:
key => I
value => 50
Or use a loop:
<?php
$value = [];
foreach ($pair as $k => $v) {
if (!empty($v)) {
$value[$k] = $v;
break;
}
}
if (!empty($value)) {
echo 'key => '.array_keys($value)[0].PHP_EOL;
echo 'value => '.array_values($value)[0];
}
https://3v4l.org/tPeAq
Result:
key => I
value => 50
Or use a generator,
<?php
$getNoneEmpty = function() use ($pair) {
foreach ($pair as $key => $value) {
if (!empty($value)) {
yield [$key => $value];
}
}
};
// get first
$value = $getNoneEmpty()->current();
if (!empty($value)) {
echo 'key => '.array_keys($value)[0].PHP_EOL;
echo 'value => '.array_values($value)[0].PHP_EOL;
}
// or loop over all
foreach ($getNoneEmpty() as $value) {
echo 'key => '.array_keys($value)[0].PHP_EOL;
echo 'value => '.array_values($value)[0].PHP_EOL;
}
https://3v4l.org/mnnHl
Result:
key => I
value => 50
key => I
value => 50
key => P
value => 30
Many ways to skin a cat, though, if you don't want the key/value you can also do it differently.
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";
}
I have nested associative array with more than 4 levels. Some values goes to all 4 levels while some ends on first level. Now how do I access all values from php.
For 2 levels array I can just:
foreach($options as $o){
foreach($m as $check){
if(isset($check[$o])) echo $check[$o];
}
}
to check if a value is set and then use it.
But how do I do this for the array having unknown depth or a lot of levels with uneven level.
It depends by what you mean with 'access'. If you just want to print out the values you could use a recursive function like this:
function crawlArray($myArray, $depth=0) {
foreach ($myArray as $k => $v) {
if (is_array($v)) {
crawlArray($v, ++$depth);
} else {
echo $v;
}
}
}
crawlArray($options);
You can use a recursive function as so:
<?php
function getSetValues($array, $searchKeys) {
$values = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$values = array_merge($values, getSetValues($value, $searchKeys));
} else if (in_array($key, $searchKeys)) {
$values[] = $value;
}
}
return $values;
}
$values = getSetValues(array(
'foo' => array(
'bar' => 123,
'rab' => array(
'oof' => 'abc'
),
'oof' => 'cba'
),
'oof' => 912
), array('bar', 'oof')); //Search for keys called 'bar' or 'oof'
print_r($values);
?>
Which will output:
Array
(
[0] => 123 (because the key is 'bar')
[1] => abc (because the key is 'oof')
[2] => cba (because the key is 'oof')
[3] => 912 (because the key is 'oof')
)
DEMO
I need some help reading the values from multidimension arrays. The array looks like below.
Array
(
[translations] => Array
(
[0] => Array
(
[translatedText] => fantasma
[detectedSourceLanguage] => en
)
)
)
I tried the following, but kept on getting blanks. Any help be appreciated?
foreach($item as $translations)
{
foreach($row['0'] as $k)
{
echo $k['translatedText'];
echo $k['detectedSourceLanguage'];
}
}
When working with foreach loops, you want to call the array you plan on iterating over with the following syntax:
foreach($array as $variable){ }
Array being the array you plan on going through, and the variable being the variable you are planning to call it as within the foreach.
More information on foreach loops can be found at PHP:foreach
With that said, try the code below:
$data = array(
"translations" => array(
array("translatedText" => "fantasma",
"detectedSourceLanguage" => "en"
)
)
);
echo "<pre>";
echo print_r($data);
echo "</pre>";
foreach($data["translations"] as $translation) {
echo $translation['translatedText'] . "<br />";
echo $translation['detectedSourceLanguage'] . "<br />";
}
//Or, if the $data variable will be holding multiple translation arrays:
foreach($data as $d) {
foreach($d as $translation){
echo $translation['translatedText'];
echo $translation['detectedSourceLanguage'];
}
}
Try this:
foreach ($item['translations'] as $translation) {
echo $translation['translatedText'];
echo $translation['detectedSourceLanguage'];
}
See DEMO
Change your code to below :
$test = Array(
"translations" => Array (
"0" => Array (
"translatedText" => "fantasma",
"detectedSourceLanguage" => "en"
)
)
);
foreach ($test as $translations) {
foreach ($translations as $k) {
echo $k["translatedText"];
echo "<br/>";
echo $k["detectedSourceLanguage"];
}
}
This should work.
Follow this for more info about array : http://php.net/manual/en/language.types.array.php
The issue is that you are not defining the $row variable. The good news is that you don't need it.
You can simply do this:
foreach($item as $translations => $values)
{
foreach($values as $k)
{
echo $k['translatedText']."\n";
echo $k['detectedSourceLanguage'];
}
}