How to print out Multi-Dimensional Arrays in php - php

Consider the array is:
Array
(
[Page-1] => Array
(
[0] => Array
(
[0] => Cat-1
[1] => Item-1
)
)
[Page-2] => Array
(
[0] => Array
(
[0] => Cat-2
[1] => Item-2
)
[1] => Array
(
[0] => Cat-3
[1] => Item-3
)
[2] => Array
(
[0] => Cat-4
[1] => Item-4
)
)
[Page-3] => Array
(
[0] => Array
(
[0] => Cat-5
[1] => Item-5
)
)
[Page-4] => Array
(
[0] => Array
(
[0] => Cat-6
[1] => Item-6
)
)
[Page-5] => Array
(
[0] => Array
(
[0] => Cat-7
[1] => Item-7
)
[1] => Array
(
[0] => Cat-9
[1] => Item-9
)
)
[Page-6] => Array
(
[0] => Array
(
[0] => Cat-8
[1] => Item-8
)
)
)
Where, the first keys [Page-x] from array will be Main-Links in the navigation menu.
Some of the main links may have Sub-Links, some not.
Sub-links are the values of the key [0] of the 3rd sub-array.
And finally the URL for each and every link will be the value of key [1] of the 3rd sub-Array.
Only Pages that have more than one category will show its categories as sub-links
The navigation bar i would like to have:
1. Page-1
2. Page-2
Cat-2
Cat-3
Cat-4
3. Page-3
4. Page-4
5. Page-5
Cat-7
Cat-9
6. Page-6
the PHP code
$records = $p->main_links();
foreach ($records as $key => $value) {
$return[$value['page']][] = array($value['child'], $value['item']);
}
foreach ($return as $key2 => $value2) {
$count = 0;
/* Select a specific value within the Array */
$main_links = $value2[$count][1]; /* URL of the main Pages */
$count = count($return[$key2]);
if($count > 1) {
foreach ($value2 as $key3 => $value3)
{
$link_name = $value3[0]; /* Child Link Names */
$link_url = $value3[1]; /* URL of Child Links */
/* addedd htmlspecialchars() function to $variables that will be echoed into HTML. It provides some XSS protection */
$cat_link .= '<li>'.htmlspecialchars($link_name).'</li>';
}
$result .= '
<li '.htmlspecialchars($li_class).'><span>'.htmlspecialchars($key2).'</span>
<ul>
'.$cat_link.'
</ul>
</li>';
}else {
$result .= '
<li><span>'.htmlspecialchars($key2).'</span></li>';
}
}
Unfortunately i can't get it work... the output is not what i am expecting :(
current Output (wrong one):
1. Page-1
2. Page-2
Cat-2
Cat-3
Cat-4
3. Page-3
4. Page-4
5. Page-5
Cat-2
Cat-3
Cat-4
Cat-7
Cat-9
6. Page-6
Any help would be appreciated!

Your current code is close to working. This line will always produce a count of 1.
$count = count($value);
What you're looking for there, I believe, is:
$count = count($return[$key]);

I've found another way around which is way better than the one i was trying to do. This solved my case.
http://wizardinternetsolutions.com/articles/web-programming/single-query-dynamic-multi-level-menu
Thank you for your support!

Related

How do I add keys recursively to an array

I have a query result set which I loop through. Depending on the data inside the result set, I want to add it to the array, or if the specific value contains an ID, loop again, and add it at the current position. I want to end up with something like this.
Array
(
[0] => Array
(
[title] => Array
(
[0] => Array
(
[value] => Lorem ipsum
)
)
[uid] => Array
(
[0] => Array
(
[uid] => Array
(
[value] => 1
)
[field_name] => Array
(
[value] => John Doe
)
)
)
)
)
I accomplished the result, but I'm looping over and over again, I would like it to be recursive. So I ended up doing something like this.
foreach ($fields as $nr => $field){
if ($field_type == 'entity_reference'){
// Query again
...
foreach ($fields2 as $nr2 => $field2){
if ($field_type2 == 'entity_reference'){
// Query again
...
} else {
$return[$nr][$field][$nr2][$fieldl2] = $value2;
}
}
} else {
$return[$nr][$field][] = $value;
}
}
How can I make it recursive, so I don't have to loop many times?

Creating and pushing to arrays

I am trying to create an array(if it does not already exist) and then push values to it.
foreach($playlist->items as $item) {
$str = $item->snippet->title;
$id = $item->snippet->resourceId->videoId;
$substring = substr($str, 0, 5);
$substring = strtolower($substring);
if (is_array($substring)) {
array_push($substring, $id);
}
else {
$substring = array();
array_push($substring, $id);
}
array_push($artists, $substring);
}
I am iterating through data retrieved from a Youtube playlist, so I go through each item with foreach which holds a 'title' - the artist and an 'id' - the video Id . I substring each title and try to use this to group artists into specific arrays.
If an array already exists for that artist, I try to push the 'id' onto the end of that array. If an array does not exist, I create one and then push the 'id' onto that array.
At the end I try to push each artist array into the 'artists' array.
What I get when I print out $artists array is something like this
Array
(
[0] => Array
(
[0] => 1_YUrdjLyAU
)
[1] => Array
(
[0] => Gp8lDW2LUM0
)
...
[543] => Array
(
[0] => Exa0CzlCb3Y
)
Every single $id is in it's own array when they should be grouped together based on $substring. e.g
Array
(
[0] => Array
(
[0] => 1_YUrdjLyAU
[1] => 1_YUrdjLyAU
[2] => 1_YUrdjLyAU
[3] => 1_YUrdjLyAU
[4] => 1_YUrdjLyAU
)
[1] => Array
(
[0] => Gp8lDW2LUM0
[1] => 1_YUrdjLyAU
[2] => 1_YUrdjLyAU
[3] => 1_YUrdjLyAU
)
What am I not understanding?
Here is a simpler solution to your problem:
$artists = array();
foreach($playlist->items as $item) {
$artist = $item->snippet->artist; // however the artist name is fetched..
$id = $item->snippet->resourceId->videoId;
$artists[$artist][] = $id
}
This way, you don't need to check if an artist is already in the array, it will do that automatically and append the video id to the artist.
The $artists array will be assosiative, I don't think you can do it with a numeric array.
The array will look like this:
Array
(
['Jon Lajoie'] => Array
(
[0] => 1_YUrdjLyAU
[1] => lf3hflkap39
[2] => 1vt1455zzbe
[3] => 6dthg3drgjb
[4] => jfop3ifjf3p
)
['Lonely Island'] => Array
(
[0] => Gp8lDW2LUM0
[1] => 5he5hj67j7r
[2] => krt7tkktzk8
[3] => we54w4ggsrg
)
)
Use substring as array key and do following:
**Remove**
if (is_array($substring)) {
array_push($substring, $id);
}
else {
$substring = array();
array_push($substring, $id);
}
array_push($artists, $substring);
**Replace**
$artist[$substring][]=$id;

Getting values from array

I know this is a newbie question,
I extracted some preformatted json out of javascript, that looks like this:
[[[455837.99,2896882.36],[455862.44,2896888.35],[455868.79,2896860.14],[455864.3,2896852.78],[455845.76,2896848],[455837.99,2896882.36]]]
I tried an online formatted that shows me the array looks something like this:
Array
(
[0] => Array
(
[0] => Array
(
[0] => 455837.99
[1] => 2896882.36
)
[1] => Array
(
[0] => 455862.44
[1] => 2896888.35
)
[2] => Array
(
[0] => 455868.79
[1] => 2896860.14
)
[3] => Array
(
[0] => 455864.3
[1] => 2896852.78
)
[4] => Array
(
[0] => 455845.76
[1] => 2896848
)
[5] => Array
(
[0] => 455837.99
[1] => 2896882.36
)
)
)
All the third [0]'s are what I need as an X, so everything that starts with 455. and All the [1]'s are the Y's. I would like these two to be grouped together, the respective X and Y.
My problem is I am not sure how to access them out of the area, I have tried this:
preg_match_all('/\[{3}.*\]{3}/', $data, $matches);
$arr=array();
foreach ($matches[0] as $match)
{
$arr[]=json_decode($match);
}
echo '<br>';
$newmatch = json_decode($match);
I would really appreciate if someone can point me in the direction of being able to have a loop that basically echo's the X and Y values, whenever I try and echo something from the array I get:
1) Array to string conversion
I am not sure if that is because of the triple brackets, that its an array in an array in an array.
$data = "[[[455837.99,2896882.36],[455862.44,2896888.35],[455868.79,2896860.14],[455864.3,2896852.78],[455845.76,2896848],[455837.99,2896882.36]]]";
$data_array = json_decode($data);
if (is_array($data_array) && array_key_exists(0, $data_array)) {
foreach ($data_array[0] as $element) {
$x = array_key_exists(0, $element) ? $element[0] : "N/A";
$y = array_key_exists(1, $element) ? $element[1] : "N/A";
printf("X: %s | Y: %s\n", $x, $y);
}
}

PHP: array_splice() not giving me correct output

I'm trying to experiment with array_splice and I get an output like this (from $match)
Array
(
[Keep me Updated] => Array
(
[winner] => winnerl.jpg
[0] => value0.jpg
)
[0] => valuel.jpg //this should really be inside [Leep me Updated] array
[1] => value2.jpg //this should really be inside [Leep me Updated] array
[2] => value3.jpg //this should really be inside [Leep me Updated] array
}
from (this foreach creates puts in the values into $match)
foreach($data as $d)
{
if (isset($match[$d['data']['name']])) {
$match_loser = array($d['loser']['lrg_img']);
array_splice($match,1,0,$match_loser);
}else{
$match[$d['data']['name']] = array("winner"=>$d['winner']['lrg_img'],
$d['loser']['lrg_img']);
}
}
What I'm trying to get is bring [0],[1],[2] into the [Keep me Updated] $match array:
Array
(
[Keep me Updated] => Array
(
[winner] => winnerl.jpg
[0] => value0.jpg
[1] => value1.jpg // old one: [0] => valuel.jpg
[2] => value2.jpg // old one: [1] => value2.jpg
[3] => value3.jpg // old one: [2] => value3.jpg
)
}
This is what $data looks like
$data[] = array(
"data"=>array
(
"name"=>$name,
),
"winner"=>array
(
"lrg_img"=>$img_url_winner
),
"loser"=>array
(
"lrg_img"=>$img_url_loser
)
$data has array values, and $match is where I'm trying to sort the data. So if my values match, it'll consolidate.
Thanks!
Use the inner array as the argument to array_splice
foreach($data as $d)
{
if (isset($match[$d['data']['name']])) {
$match_loser = array($d['loser']['lrg_img']);
array_splice($match[$d['data']['name']],1,0,$match_loser);
}else{
$match[$d['data']['name']] = array("winner"=>$d['winner']['lrg_img'],
$d['loser']['lrg_img']);
}
}

Problem with Building Arrays in Different Coding Styles

I'm having a strange problem while building arrays. I start off with an array that looks like this:
Array (
[0] => Array (
[tag_id] => 19
[tag_translation_id] => 12
[fk_language_id] => 1
[fk_tag_id] => 19
[tag_name] => test
)
[1] => Array (
[tag_id] => 20
[tag_translation_id] => 14
[fk_language_id] => 1
[fk_tag_id] => 20
[tag_name] => testa
)
[2] => Array (
[tag_id] => 20
[tag_translation_id] => 15
[fk_language_id] => 3
[fk_tag_id] => 20
[tag_name] => fdfda
)
)
What I want to do is merge each result with the same tag_id into a single array. This works:
$tags = array();
foreach($results->as_array() as $key=>$result)
{
if(!in_array($result['tag_id'], $tags))
{
$tags[$result['tag_id']] = array();
}
}
foreach($results->as_array() as $result)
{
array_push($tags[$result['tag_id']], array($result['fk_language_id'] , $result['tag_name']));
}
Here is the intended result:
Array (
[19] => Array (
[0] => Array (
[0] => 1
[1] => test
)
)
[20] => Array (
[0] => Array (
[0] => 1
[1] => testa
)
[1] => Array (
[0] => 3
[1] => fdfda
)
)
)
However, I've got two loops here, and I know this isn't ideal. Why do THESE not work??
$tags = array();
foreach($results->as_array() as $key=>$result)
{
$tags[$result['tag_id']] .= array($result['fk_language_id'] , $result['tag_name']);
}
With this example I get two empty arrays...
Array ( [19] => Array [20] => ArrayArray )
Or even...
$tags = array();
foreach($results->as_array() as $key=>$result)
{
if(!in_array($result['tag_id'], $tags))
{
$tags[$result['tag_id']] = array();
}
array_push($tags[$result['tag_id']], array($result['fk_language_id'] , $result['tag_name']));
}
Which for some reason overwrites the first value of the second array with the second value of the second array.
Array (
[19] => Array (
[0] => Array (
[0] => 1
[1] => test
)
)
[20] => Array (
[0] => Array (
[0] => 3
[1] => fdfda
)
)
)
What am I doing wrong in the second 2 examples?
To answer your question, your second method fails because you're using the incorrect .= operator. Your third method fails because your !in_array check is always false (it checks whether the value is in the array, not whether the key is set) and overwrites the array each iteration. You only really need this (as mentioned by others, in pseudo-code):
$result = array();
foreach ($array as $values) {
$result[$values['key']][] = array($values['foo'], $values['bar']);
}
The .= operator is string concatenation. Arrays are merged with +=.
If I understand the issue correctly, the code should go like this:
$tags = array();
foreach ($results as $result)
$tags[$result['tag_id']][] = array($result['fk_language_id'], $result['tag_name']);
$tags = array();
foreach($results->as_array() as $key=>$result)
{
$tags[$result['tag_id']] .= array($result['fk_language_id'] , $result['tag_name']);
}
you cannot add a value to an array with the .= (dot equal) operator.
why are you doing $results->as_array() ????
do simply:
foreach($results as $key=>$result) {
Instead of using .= try using []
$tags = array();
foreach ($results as $result)
{
if(!isset($tags[$result['tag_id']]))
$tags[$result['tag_id']] = array();
$tags[$result['tag_id']][] = array($result['fk_language_id'], result['tag_name']);
}
.= is to concatinate a string
+= is to concatinate a number
[] is to concatinate to an array
Hope this helps?
Edit: Noticed that it "might" fail if the tag_id doesn't already exist in the array, so it might be worth just checking first and setting it to an array just in case.

Categories