reading multiple arrays in PHP - php

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'];
}
}

Related

how to get the key and value in the object in list of array

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.

How to echo the key:value pairs of a sub array? PHP

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>";
}

PHP - Foreach does echo the values but do not push it to array

I have an array $x that looks somehting like this:
Array
(
[0] => Array
(
[Id] => 280123736
[BuyItNowPrice] => 600
[SellerId] => 3635925
)
[1] => Array
(
[Id] => 280195277
[SellerId] => 4269145
)
[2] => Array
(
[Id] => 280195291
[SellerId] => 4269145
)
)
Now, I want to push all values with key "Id" to a new array but I can't get it to work. I have a function that recursively go through the array like so:
$ids = array();
function get_ids($arr) {
if ($arr) {
foreach ($arr as $key => $value) {
if (is_array($value)) {
get_ids($value);
} else {
if ($key == "Id") {
//None of these seem to work
//Tried them both separately of course
$ids[] = $value;
array_push($ids, $value);
//But printing out the values does work
echo "[". $key ."]: " . $value . "\n";
}
}
}
}
}
And I call the function like so:
echo "--Call get_ids() \n";
get_ids($x);
echo "--Print $ids \n";
print_r($ids);
echo "--Print $ids length \n";
count($ids);
The output of this is:
--Call get_ids()
[Id]: 280123736
[Id]: 280195277
[Id]: 280195291
--Print $ids
Array
(
)
--Print $ids length
(No output here..)
I console.log the result with javascript calling the php script through AJAX if that is something that matters, like so:
$.ajax ({
url: "script.php",
success: function(result) {
console.log(result);
}
});
However I need to extract the "Ids" in the php script. Any suggestions?
Just use this to get all Ids into an array:
$ids = array_column($x, 'Id');
As for the foreach approach, it is much simpler as well:
foreach($x as $value) {
if(isset($value['Id'])) {
$ids[] = $value['Id'];
}
}

echoing out two dimensional associative arrays in php

I would like the data to be echoed out in this format
[0] - [name][description]
[1] - [name][description]
[2] - [name][description]
$options = array('guide_info' => $guide_info);
$guide_info = array( 'guide_name' => $guide_name,
'guide_description' => $guide_description
);
I created two foreach loops to try and echo out the name and description of each, like this:
foreach ($options as $key => $value) {
foreach ($guide_info as $type => $info){
$html .= $type . " " . $info . "\n";
}
}
but I receive errors about invalid argument supplied for foreach() on the second loop.
Currently my print_r($options) shows
Array ( [guide_name] => f
[guide_description] => fff
[0] => Array (
[guide_name] => fsss
[guide_description] => sssss
)
)
and my echo prints
guide_name fsss
guide_description sssss
guide_name fsss
guide_description sssss
guide_name fsss
guide_description sssss
How would I be able to echo out the correct information that print_r is showing?
Use a recursive function to echo out the name and description values in the desired format.
function process_array($arr, $counter){
foreach($arr as $key => $value){
if(is_array($value)){
process_array($value, ++$counter);
}else{
if($key == "guide_name"){
echo "[" . $counter . "] - [" . $value . "][";
}else{
echo $value . "]<br />";
}
}
}
}
// Here $options is your original array
process_array($options, 0);
Output:
[0] - [f][fff]
[1] - [fsss][sssss]
$guide_info = array( 'guide_name' => 'guid name',
'guide_description' => 'guid description',
);
$options = array('guide_info' => $guide_info);
foreach ($options as $key => $value) {
foreach($value as $a => $b) {
echo $a," =",$b ;
}
}
or for print_r
foreach ($options as $key => $value) {
print_r($value) ;
}
Why are you putting the $guide_info in $options.If you want all the entries from $guide_info, you can do this-
for($i = 0; $i < count($guide_info); $i++){
$html .= $type . " " . $info . "\n";
}
-> considering $guide_info is a multidimensional array like = array( [0] => 'guide_name' => $guide_name,
'guide_description' => $guide_description)
If for some reason $guide_info IS important, I would suggest it to be an indexed array not assoc.. Hope you find the solution :)

Display an array in a readable/hierarchical format [duplicate]

This question already has answers here:
Is there a pretty print for PHP?
(31 answers)
Closed 7 months ago.
Here is the code for pulling the data for my array
<?php
$link = mysqli_connect('localhost', 'root', '', 'mutli_page_form');
$query = "SELECT * FROM wills_children WHERE will=73";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
if($row = mysqli_fetch_assoc($result)) {
$data = unserialize($row['children']);
}
/* free result set */
mysqli_free_result($result);
}
?>
When I use print_r($data) it reads as:
Array ( [0] => Array ( [0] => Natural Chlid 1 [1] => Natural Chlid 2 [2] => Natural Chlid 3 ) )
I would like it to read as:
Natural Child 1
Natural Child 2
Natural Child 3
Instead of
print_r($data);
try
print "<pre>";
print_r($data);
print "</pre>";
print("<pre>".print_r($data,true)."</pre>");
I have a basic function:
function prettyPrint($a) {
echo "<pre>";
print_r($a);
echo "</pre>";
}
prettyPrint($data);
EDIT: Optimised function
function prettyPrint($a) {
echo '<pre>'.print_r($a,1).'</pre>';
}
EDIT: Moar Optimised function with custom tag support
function prettyPrint($a, $t='pre') {echo "<$t>".print_r($a,1)."</$t>";}
Try this:
foreach($data[0] as $child) {
echo $child . "\n";
}
in place of print_r($data)
I think that var_export(), the forgotten brother of var_dump() has the best output - it's more compact:
echo "<pre>";
var_export($menue);
echo "</pre>";
By the way: it's not allway necessary to use <pre>. var_dump() and var_export() are already formatted when you take a look in the source code of your webpage.
if someone needs to view arrays so cool ;) use this method.. this will print to your browser console
function console($obj)
{
$js = json_encode($obj);
print_r('<script>console.log('.$js.')</script>');
}
you can use like this..
console($myObject);
Output will be like this.. so cool eh !!
foreach($array as $v) echo $v, PHP_EOL;
UPDATE: A more sophisticated solution would be:
$test = [
'key1' => 'val1',
'key2' => 'val2',
'key3' => [
'subkey1' => 'subval1',
'subkey2' => 'subval2',
'subkey3' => [
'subsubkey1' => 'subsubval1',
'subsubkey2' => 'subsubval2',
],
],
];
function printArray($arr, $pad = 0, $padStr = "\t") {
$outerPad = $pad;
$innerPad = $pad + 1;
$out = '[' . PHP_EOL;
foreach ($arr as $k => $v) {
if (is_array($v)) {
$out .= str_repeat($padStr, $innerPad) . $k . ' => ' . printArray($v, $innerPad) . PHP_EOL;
} else {
$out .= str_repeat($padStr, $innerPad) . $k . ' => ' . $v;
$out .= PHP_EOL;
}
}
$out .= str_repeat($padStr, $outerPad) . ']';
return $out;
}
echo printArray($test);
This prints out:
[
key1 => val1
key2 => val2
key3 => [
subkey1 => subval1
subkey2 => subval2
subkey3 => [
subsubkey1 => subsubval1
subsubkey2 => subsubval2
]
]
]
print_r() is mostly for debugging. If you want to print it in that format, loop through the array, and print the elements out.
foreach($data as $d){
foreach($d as $v){
echo $v."\n";
}
}
This may be a simpler solution:
echo implode('<br>', $data[0]);
This tries to improve print_r() output formatting in console applications:
function pretty_printr($array) {
$string = print_r($array, TRUE);
foreach (preg_split("/((\r?\n)|(\r\n?))/", $string) as $line) {
$trimmed_line = trim($line);
// Skip useless lines.
if (!$trimmed_line || $trimmed_line === '(' || $trimmed_line === ')' || $trimmed_line === 'Array') {
continue;
}
// Improve lines ending with empty values.
if (substr_compare($trimmed_line, '=>', -2) === 0) {
$line .= "''";
}
print $line . PHP_EOL;
}
}
Example:
[activity_score] => 0
[allow_organisation_contact] => 1
[cover_media] => Array
[image] => Array
[url] => ''
[video] => Array
[url] => ''
[oembed_html] => ''
[thumb] => Array
[url] => ''
[created_at] => 2019-06-25T09:50:22+02:00
[description] => example description
[state] => published
[fundraiser_type] => anniversary
[end_date] => 2019-09-25
[event] => Array
[goal] => Array
[cents] => 40000
[currency] => EUR
[id] => 37798
[your_reference] => ''
I assume one uses print_r for debugging. I would then suggest using libraries like Kint. This allows displaying big arrays in a readable format:
$data = [['Natural Child 1', 'Natural Child 2', 'Natural Child 3']];
Kint::dump($data, $_SERVER);
One-liner for a quick-and-easy JSON representation:
echo json_encode($data, JSON_PRETTY_PRINT);
If using composer for the project already, require symfony/yaml and:
echo Yaml::dump($data);
echo '<pre>';
foreach($data as $entry){
foreach($entry as $entry2){
echo $entry2.'<br />';
}
}
<?php
//Make an array readable as string
function array_read($array, $seperator = ', ', $ending = ' and '){
$opt = count($array);
return $opt > 1 ? implode($seperator,array_slice($array,0,$opt-1)).$ending.end($array) : $array[0];
}
?>
I use this to show a pretty printed array to my visitors
Very nice way to print formatted array in php, using the var_dump function.
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
I use this for getting keys and their values
$qw = mysqli_query($connection, $query);
while ( $ou = mysqli_fetch_array($qw) )
{
foreach ($ou as $key => $value)
{
echo $key." - ".$value."";
}
echo "<br/>";
}
I would just use online tools.
first do print_r(your_array)
Second copy the result and paste in http://phillihp.com/toolz/php-array-beautifier/
For single arrays you can use implode, it has a cleaner result to print.
<?php
$msg = array('msg1','msg2','msg3');
echo implode('<br />',$msg);
echo '<br />----------------------<br/>';
echo nl2br(implode("\n",$msg));
echo '<br />----------------------<br/>';
?>
For multidimensional arrays you need to combine with some sort of loop.
<?php
$msgs[] = $msg;
$msgs[] = $msg;
$msgs[] = $msg;
$msgs[] = $msg;
$msgs[] = $msg;
foreach($msgs as $msg) {
echo implode('<br />',$msg);
echo '<br />----------------------<br/>';
}
?>

Categories