How to Print multilevel array index in php - php

I have the following array:
$array=array("string",array(1,2,3),true,"php");
and I want to print indexes like:
0=>string
1.0=>1
1.1=>2
1.2=>3
2=>true
3=>php

<?php
$array=array("string",array(1,2,3),true,"php");
foreach($array as $key=>$value)
{
if(is_array($value))
{
foreach($value as $childkey=>$childvalue)
{
echo $key . "." . $childkey . "=>" . $childvalue . "\n";
}
}
elseif(is_bool($value))
{
echo $key . "=>" . ($value ? "true" : "false") . "\n";
}
else
{
echo $key . "=>" . $value . "\n";
}
}
Output:
0=>string
1.0=>1
1.1=>2
1.2=>3
2=>true
3=>php

Try this
<?php
$array=array("string",array(1,2,3),true,"php");
foreach($array as $key=>$value){
if(is_array($value)){
foreach($value as $key1=>$value1){
echo $key.".".$key1." => ".$value1."</br>";
}
}
else{
echo $key." => ".$value."</br>";
}
}

<?php
$array=array("string",array(1,2,3),"true","php");
foreach($array as $key=>$value){
if(is_array($value)){
foreach($value as $key1=>$loop){
echo $key.'.'.$key1 .'=>'.$loop."<br>";
}
}else{
echo $key .'=>'.$value."<br>";
}
}
?>

Try this code
$array=array("string",array(1,2,3),true,"php");
foreach($array as $key=>$val){
if(is_array($val)){
foreach($val as $key1=>$val1){
echo $key.'.'.$key1 .'=>'.$val1.'<br/>';
}
}else{
echo $key .'=>'.$val.'<br/>';
}
}

You can try this-
<?php
$arr=array("string",array(1,2,3),true,"php");
$res=convArray($arr);
foreach($res as $k=>$v){
echo $k."=>".$v."\n";
}
function convArray($arr)
{
foreach($arr as $k1=>$v1){
if(is_array($v1)){
foreach($v1 as $k2=>$v2){
$res[$k1.'.'.$k2]=$v2;
}
}else{
$res[$k1]=$v1;
}
}
return $res;
}
?>

Try this:
<?php
$array=array("string",array(1,2,3,array('a','b','c')),true,"php");
$kt = array();
function showarray($arr,$k) {
global $kt;
foreach($arr as $key => $v) {
$nk = $k == '' ? $key:$k.'.'.$key;
if(is_array($v)) {
showarray($v,$nk);
} else {
$kt[$nk] = $v;
}
}
}
showarray($array,"");
print_r($kt);

Related

Iterate through Nested array in PHP

I have a nested array on this link Array Sample
I am using code below to parse this, but second and beyond depth it's returning nothing. However tried with recursive function.
printAllValues($ArrXML);
function printAllValues($arr) {
$keys = array_keys($arr);
for($i = 0; $i < count($arr); $i++) {
echo $keys[$i] . "$i.{<br>";
foreach($arr[$keys[$i]] as $key => $value) {
if(is_array($value))
{
printAllValues($value);
}
else
{
echo $key . " : " . $value . "<br>";
}
}
echo "}<br>";
}
}
What I am doing Wrong? Please help.
Version of J. Litvak's answer that works with SimpleXMLElement objects.
function show($array) {
foreach ($array as $key => $value) {
if (!empty($value->children())) {
show($value);
} else {
echo 'key=' . $key . ' value=' . $value. "<br>";
}
}
}
show($ArrXML);
You can use recurcive function to print all values:
function show($array) {
foreach( $array as $key => $value) {
if (is_array($value)) {
show($value);
} else{
echo 'key=' . $key . ' value=' . $value. "<br>";
}
}
}
show($ArrXML);

Php foreach in_array keeps returning false

I built a foreach which loops through a specific folder and gets an array:
foreach ($watchFolder as $key => $value) {
echo '<pre>';
print_r($value);
echo '</pre>';
if((in_array('xml', $watchFolder))) {
echo "true";
} else {
echo "false";
}
foreach ($value as $key => $valueSub) {
$currentWatchPath2 = $currentWatchPath . '\\' . $key;
foreach ($valueSub as $content) {
$currentWatchPath3 = $currentWatchPath2 . '\\' . $content;
}
}
}
If I print out the $watchfolder I get this:
Array (
[test] => Array([videos] => Array()
[xml] => Array())
[test2] => Array([json] => Array([0] => test.json)
[videos] => Array())
)
If I try this:
dd(in_array('xml', $value));
it returns null, whereas it should return true or?
I am really confused at the moment, so I appreciate every tips and suggestion.
xml is a key of $value array so I think you should check like this:
foreach ($watchFolder as $key => $value) {
echo '<pre>';
print_r($value);
echo '</pre>';
if(isset($value['xml'])) { // <--- here is the changed.
echo "true";
} else {
echo "false";
}
foreach ($value as $key => $valueSub) {
$currentWatchPath2 = $currentWatchPath . '\\' . $key;
foreach ($valueSub as $content) {
$currentWatchPath3 = $currentWatchPath2 . '\\' . $content;
}
}
}
In replace of in_array('xml', $watchFolder), it would be used in_array('xml', $value)
foreach ($watchFolder as $key => $value) {
echo '<pre>';
print_r($value);
echo '</pre>';
if((in_array('xml', $value))) {
echo "true";
} else {
echo "false";
}
foreach ($value as $key => $valueSub) {
$currentWatchPath2 = $currentWatchPath . '\\' . $key;
foreach ($valueSub as $content) {
$currentWatchPath3 = $currentWatchPath2 . '\\' . $content;
}
}
}

XML: Show two child nodes with the same name in php

I have a problem with showing my xml into a php page. I have an xml that looks like this (obviously its only a part of it because it really to long to post it all).
It all goes well until it cames to the "genre", I have two values for it and I don't know how to show them at the same time.
<movie>
<id>4441</id>
<title>Rudderless</title>
<title_long>Rudderless (2014)</title_long>
<year>2014</year>
<rating>7.5</rating>
<runtime>105</runtime>
<genres>
<genre>Comedy</genre>
<genre>Drama</genre>
</genres>
</movie>
(an important thing to notice is that not every movie will have two genre, sometimes there is only one and sometime two or three)
This is my code right now
$genere = array();
foreach ($xml->data->movies->movie->genres as $row) {
foreach ($row->children() as $key => $val) {
if ($key == "genre") {
$genere[] = $val;
}
}
}
//and then I'll print
for ($i = 0; $i < 20 ; $i++) {
echo "<div class=text><b>" . $genere[$i] . "</b></div>";
}
When I'm doing this it will print only for the first item of the array, and the others just give me a "Notice: Undefined offset: 1 in /path/ on line 53"
I've tried to follow some guides but it was a failure
What am I doing wrong?
/--Edit--/
<?php
$xml = simplexml_load_file("https://yts.to/api/v2/list_movies.xml")
$titolo = array();
$locandina = array();
$anno = array();
$durata = array();
$genere = array();
foreach ($xml->data->movies->movie as $element)
{
foreach($element->children() as $key => $val)
{
$chiave = $key;
$valore = $val;
if ($key == "title")
{
$titolo[] = $val ;
}
if ($key == "medium_cover_image")
{
$locandina[] = $val ;
}
if ($key == "year")
{
$anno[] = $val ;
}
if ($key == "runtime")
{
$durata[] = $val;
}
}
}
foreach ($xml->data->movies->movie->genres as $row)
{
foreach($row->children() as $key => $val)
{
if ($key == "genre")
{
$genere[] = $val;
}
}
}
var_dump($genere);
for ($i=0 ; $i<20 ; $i++)
{
echo "<div class=totbox>";
echo "<div class=box><img src=" . $locandina[$i] . "></div>";
echo "<div class=text><b>" . $titolo[$i] . "</b> - " . $anno[$i] . "</div>";
echo "<div class=text><b>" . $genere[$i] . "</b></div>";
echo "<div class=text><b> Durata:" . $durata[$i] . "</b></div>";
echo "</div>";
}
?>
UPDATED - Code fixed. Please, try now.
<?php
$xml = simplexml_load_file("https://yts.to/api/v2/list_movies.xml")
$titolo = array();
$locandina = array();
$anno = array();
$durata = array();
$genere = array();
$i = 0;
foreach ($xml->data->movies->movie as $element) {
foreach ($element->children() as $key => $val) {
$chiave = $key;
$valore = $val;
if ($key == "title") {
$titolo[] = $val;
}
if ($key == "medium_cover_image") {
$locandina[] = $val;
}
if ($key == "year") {
$anno[] = $val;
}
if ($key == "runtime") {
$durata[] = $val;
}
if ($key == "genres") {
for($g = 0; $g < count($xml->data->movies->movie[$i]->genres->genre); $g++) {
$genere[$i][] = $xml->data->movies->movie[$i]->genres->genre[$g];
}
}
}
$i++;
}
for ($i = 0; $i < count($titolo); $i++) {
echo "<div class=totbox>";
if (isset($locandina[$i])) {
echo "<div class=box><img src=" . $locandina[$i] . "></div>";
}
echo "<div class=text><b>" . $titolo[$i] . "</b> - " . $anno[$i] . "</div>";
foreach ($genere[$i] as $genResult) {
echo "<div class=text><b>" . $genResult . "</b></div>";
}
echo "<div class=text><b> Durata:" . $durata[$i] . "</b></div>";
echo "</div>";
}
I hope this helps!
Look on my code, based on yours. PHP file:
<?php
$xml = new SimpleXMLElement(file_get_contents('test.xml'));
$genere = array();
foreach ($xml->genres as $row) {
foreach ($row->children() as $key => $val) {
if ($key == "genre") {
$genere[] = $val;
}
}
}
//and then I'll print
foreach ($genere as $genre) {
echo "<div class=text><b>" . $genre . "</b></div>";
}
XML file:
<movie>
<id>4441</id>
<title>Rudderless</title>
<title_long>Rudderless (2014)</title_long>
<year>2014</year>
<rating>7.5</rating>
<runtime>105</runtime>
<genres>
<genre>Comedy</genre>
<genre>Drama</genre>
</genres>
</movie>
Its work fine, test it.
Based on your full xml file, look on this:
<genres>
<genre>Horror</genre>
</genres>
You have only one genre on first position, so its work fine. You need to loop on movie tag first, not genres. So put your genre tag inside movie foreach.
Like:
foreach($element->children() as $key => $val)
{
if ($key == "genres")
{
// your loop, based on $val variable!
}

Array inside assosiative array

I want to create an assosiative array which it will have as one of its elements an other array (not assosiative)
$temp= array(
'elem1' => $data1,
'elem2' => $data2,
'elem3' => $data5,
);
$data2 is a simple array already constructed. However, I cannot find the right syntax for doing that. By applying the classic following I cannot get the values of elem2.
while ($element=each($temp))
{
echo $element['key'];
echo " - ";
echo $element['value'];
echo "<br/>";
}
It's not quite clear from your question, but depending on the structure of $data2, printing its values separated by commas may suffice:
foreach ($temp as $key => $value) {
echo $key, ' - ';
if (is_array($value)) {
echo implode(',', $value);
}
else {
echo $value;
}
echo '<br/>';
}
try this
$data = ['elem1' => '1', 'elem2' => ['red','blue','orange' ],'elem3' => '3'];
$tmp ='';
foreach ($data as $key => $value ) {
$tmp .= $key.' - ' ;
if (is_array($value)) {
$tmp.= implode(',', $value).' ';
}else {
$tmp .= $value. ' ';
}
}
echo json_encode($tmp);
You can echo the values in this way:
foreach($temp as $key => $value) {
echo $key;
echo " - ";
if(is_array($value)) {
echo "Array: # ";
foreach($value as $value_key => $value_value) {
echo $value_key." - ".$value_value." # ";
}
} else {
echo $value;
}
echo "<br/>";
}

Count duplicate values in PHP array

my problem is, i have this script
foreach ($arr1 as $k => $val) {
if (in_array($val, $arr2)) {
echo 'Obsazeno <br>';
} else {
echo $val . "<BR>";
}
}
Where $arr1 is generated array of days and $arr2 is array from mysql results. Actually it works fine. If one of days from $arr1 is in database, it will echo "Obsazeno" instead of day value.
But i need small upgrade. Script check if $val is in $arr2 and i need small counting contidion that will do this:
If $val is in $arr2 once - it will echo $val.
If $val is in $arr2 twice - it will echo $val.
But if $val is in $arr2 thrice - it will echo "Obsazeno".
I hope you understand my question.
I quest, it is possible by array_count_values. I try it by myself but no success.
You can achieve this with array_count_values.
$values = array_count_values($arr2);
foreach ($arr1 as $k => $val) {
if (array_key_exists($val, $values) && $values[$val] >= 3) {
echo 'Obsazeno <br>';
} else {
echo $val . '<br>';
}
}
try
$i=0;
foreach($arr1 as $k=>$val) {
if(in_array($val,$arr2)) {
$i++;
if($i == 3) {
echo 'Obsazeno <br>';
}
else {
echo $val."<BR>";
}
}
}
$data = array();
foreach($arr1 as $k=>$val)
{
if(!array_key_exists($val,$data)){
$data[$val] = 0;
}
if(in_array($val,$arr2))
{
$data[$val]++;
if($data[$val]==3){
echo 'Obsazeno <br>';
}else{
echo $val."<BR>";
}
}
else
{
echo $val."<BR>";
}
}

Categories