I have been trying to get this to work for 7.5 hours now, but my brain has melted.
I have a multi-dimensional array similar to the following:
array (
'expanded' => true,
'key' => 'root_1',
'title' => 'root',
'children' =>
array (
0 =>
array (
'folder' => false,
'key' => '_1',
'title' => 'News',
'data' =>
array (
'id' => '3',
'parent_id' => 0,
),
),
1 =>
array (
'folder' => true,
'key' => '_2',
'title' => 'Animations',
'data' =>
array (
'id' => '5',
'parent_id' => '0',
),
'children' =>
array (
0 =>
array (
'folder' => false,
'key' => '_3',
'title' => 'The Simpsons',
'data' =>
array (
'id' => '1',
'parent_id' => '5',
),
),
1 =>
array (
'folder' => false,
'key' => '_4',
'title' => 'Futurama',
'data' =>
array (
'id' => '4',
'parent_id' => '5',
),
),
),
),
2 =>
array (
'folder' => true,
'key' => '_5',
'title' => 'Episodes',
'data' =>
array (
'id' => '6',
'parent_id' => '0',
),
'children' =>
array (
0 =>
array (
'folder' => true,
'key' => '_6',
'title' => 'UK Episodes',
'data' =>
array (
'id' => '7',
'parent_id' => '6',
),
'children' =>
array (
0 =>
array (
'folder' => false,
'key' => '_7',
'title' => 'Coupling',
'data' =>
array (
'id' => '2',
'parent_id' => '7',
),
),
),
),
1 =>
array (
'folder' => true,
'key' => '_8',
'title' => 'AU Episodes',
'data' =>
array (
'id' => '8',
'parent_id' => '6',
),
),
),
),
),
)
I need to search through all sub arrays and build a new array returning the id and parent_id of each of the children AND also interpreting the order of the array children from the order they appear in the original array.
The output needs to end up something like this:
Array
(
[0] => Array
(
[id] => 1
[parent_id] => 5
[order] => 1
)
[1] => Array
(
[id] => 2
[parent_id] => 7
[order] => 1
)
[2] => Array
(
[id] => 4
[parent_id] => 5
[order] => 2
)
)
I have tried the following recursion approach, however my code turns into a mess, and thats before I've even attempted to set the order of the items.
I've also searched stackoverflow for another example that I could learn from however I haven't found anything yet... If there is another example please feel free to point me in the right direction.
I appreciate any assistance!
A super easy way to run over all these is to use a RecursiveIteratorIterator over a RecursiveArrayIterator, pluck out the 'data' arrays and add in the key as the order.
Example:
$array = []; // Your starting array with stuff in it.
$iterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($array),
RecursiveIteratorIterator::SELF_FIRST
);
$result = [];
foreach ($iterator as $key => $value) {
if (isset($value['data'])) {
$result[] = array_merge($value['data'], ['order' => $key]);
}
}
print_r($result);
Output:
Array
(
[0] => Array
(
[id] => 3
[parent_id] => 0
[order] => 0
)
[1] => Array
(
[id] => 5
[parent_id] => 0
[order] => 1
)
[2] => Array
(
[id] => 1
[parent_id] => 5
[order] => 0
)
[3] => Array
(
[id] => 4
[parent_id] => 5
[order] => 1
)
[4] => Array
(
[id] => 6
[parent_id] => 0
[order] => 2
)
[5] => Array
(
[id] => 7
[parent_id] => 6
[order] => 0
)
[6] => Array
(
[id] => 2
[parent_id] => 7
[order] => 0
)
[7] => Array
(
[id] => 8
[parent_id] => 6
[order] => 1
)
)
If i'm understanding what you're trying to do properly the below snippet should work. No need for the order key in each sub array because that's recorded automatically when you insert a new array index into $new_array.
Let me know if you have any other problems.
$new_array = [];
$current_array = []; //with all your data
foreach($current_array['children'] as $array) {
$new_array[] = [
'id' => $array['data']['id'],
'parent_id' => $array['data']['parent_id'];
];
}
Related
I'm working with Spotify API and I want to do a foreach loop for only the values in ['tracks'][0]["album"]["images"][2]['url']
How can I go about this?
I tried to do a foreach loop to retrieve value of each key associated inside the multidimensional associative array iterating through each element but can still get it to work.
Array
(
[tracks] => Array
(
[0] => Array
(
[album] => Array
(
[album_type] => album
[artists] => Array
(
[0] => Array
(
[external_urls] => Array
(
[spotify] => https://open.spotify.com/artist/4ovtyvs7j1jSmwhkBGHqSr
)
[href] => https://api.spotify.com/v1/artists/4ovtyvs7j1jSmwhkBGHqSr
[id] => 4ovtyvs7j1jSmwhkBGHqSr
[name] => Olamide
[type] => artist
[uri] => spotify:artist:4ovtyvs7j1jSmwhkBGHqSr
)
)
[external_urls] => Array
(
[spotify] => https://open.spotify.com/album/6fG2eFCgUmytQWL6umtsCh
)
[href] => https://api.spotify.com/v1/albums/6fG2eFCgUmytQWL6umtsCh
[id] => 6fG2eFCgUmytQWL6umtsCh
[images] => Array
(
[0] => Array
(
[height] => 640
[url] => https://i.scdn.co/image/ab67616d0000b27387d20b9a27d5e14d74b5cb77
[width] => 640
)
[1] => Array
(
[height] => 300
[url] => https://i.scdn.co/image/ab67616d00001e0287d20b9a27d5e14d74b5cb77
[width] => 300
)
[2] => Array
(
[height] => 64
[url] => https://i.scdn.co/image/ab67616d0000485187d20b9a27d5e14d74b5cb77
[width] => 64
)
)
[name] => Carpe Diem
[release_date] => 2020-10-07
[release_date_precision] => day
[total_tracks] => 12
[type] => album
[uri] => spotify:album:6fG2eFCgUmytQWL6umtsCh
)
[artists] => Array
(
[0] => Array
(
[external_urls] => Array
(
[spotify] => https://open.spotify.com/artist/4ovtyvs7j1jSmwhkBGHqSr
)
[href] => https://api.spotify.com/v1/artists/4ovtyvs7j1jSmwhkBGHqSr
[id] => 4ovtyvs7j1jSmwhkBGHqSr
[name] => Olamide
[type] => artist
[uri] => spotify:artist:4ovtyvs7j1jSmwhkBGHqSr
)
[1] => Array
(
[external_urls] => Array
(
[spotify] => https://open.spotify.com/artist/5yOvAmpIR7hVxiS6Ls5DPO
)
[href] => https://api.spotify.com/v1/artists/5yOvAmpIR7hVxiS6Ls5DPO
[id] => 5yOvAmpIR7hVxiS6Ls5DPO
[name] => Omah Lay
[type] => artist
[uri] => spotify:artist:5yOvAmpIR7hVxiS6Ls5DPO
)
)
[disc_number] => 1
[duration_ms] => 171764
[explicit] => 1
[external_ids] => Array
(
[isrc] => USUYG1330802
)
[external_urls] => Array
(
[spotify] => https://open.spotify.com/track/5DS9LiyEdw2zY8bM6kjjgM
)
[href] => https://api.spotify.com/v1/tracks/5DS9LiyEdw2zY8bM6kjjgM
[id] => 5DS9LiyEdw2zY8bM6kjjgM
[is_local] =>
[is_playable] => 1
[name] => Infinity (feat. Omah Lay)
[popularity] => 73
[preview_url] => https://p.scdn.co/mp3-preview/5159fa17676fc96e32db13b7680f7497d5c2f74d?cid=756f211306ad4c9a934d07c5722790b5
[track_number] => 3
[type] => track
[uri] => spotify:track:5DS9LiyEdw2zY8bM6kjjgM
)
[1] => Array
(
[album] => Array
(
[album_type] => album
[artists] => Array
(
[0] => Array
(
[external_urls] => Array
(
[spotify] => https://open.spotify.com/artist/4ovtyvs7j1jSmwhkBGHqSr
)
[href] => https://api.spotify.com/v1/artists/4ovtyvs7j1jSmwhkBGHqSr
[id] => 4ovtyvs7j1jSmwhkBGHqSr
[name] => Olamide
[type] => artist
[uri] => spotify:artist:4ovtyvs7j1jSmwhkBGHqSr
)
)
[external_urls] => Array
(
[spotify] => https://open.spotify.com/album/6fG2eFCgUmytQWL6umtsCh
)
[href] => https://api.spotify.com/v1/albums/6fG2eFCgUmytQWL6umtsCh
[id] => 6fG2eFCgUmytQWL6umtsCh
[images] => Array
(
[0] => Array
(
[height] => 640
[url] => https://i.scdn.co/image/ab67616d0000b27387d20b9a27d5e14d74b5cb77
[width] => 640
)
[1] => Array
(
[height] => 300
[url] => https://i.scdn.co/image/ab67616d00001e0287d20b9a27d5e14d74b5cb77
[width] => 300
)
[2] => Array
(
[height] => 64
[url] => https://i.scdn.co/image/ab67616d0000485187d20b9a27d5e14d74b5cb77
[width] => 64
)
)
[name] => Carpe Diem
[release_date] => 2020-10-07
[release_date_precision] => day
[total_tracks] => 12
[type] => album
[uri] => spotify:album:6fG2eFCgUmytQWL6umtsCh
)
[artists] => Array
(
[0] => Array
(
[external_urls] => Array
(
[spotify] => https://open.spotify.com/artist/4ovtyvs7j1jSmwhkBGHqSr
)
[href] => https://api.spotify.com/v1/artists/4ovtyvs7j1jSmwhkBGHqSr
[id] => 4ovtyvs7j1jSmwhkBGHqSr
[name] => Olamide
[type] => artist
[uri] => spotify:artist:4ovtyvs7j1jSmwhkBGHqSr
)
[1] => Array
(
[external_urls] => Array
(
[spotify] => https://open.spotify.com/artist/68R39izwNAztATrXMOqkJS
)
[href] => https://api.spotify.com/v1/artists/68R39izwNAztATrXMOqkJS
[id] => 68R39izwNAztATrXMOqkJS
[name] => Bad Boy Timz
[type] => artist
[uri] => spotify:artist:68R39izwNAztATrXMOqkJS
)
)
[disc_number] => 1
[duration_ms] => 194000
[explicit] => 1
[external_ids] => Array
(
[isrc] => USUYG1330809
)
[external_urls] => Array
(
[spotify] => https://open.spotify.com/track/558ULLj8yY2vT8XGtgY0q9
)
[href] => https://api.spotify.com/v1/tracks/558ULLj8yY2vT8XGtgY0q9
[id] => 558ULLj8yY2vT8XGtgY0q9
[is_local] =>
[is_playable] => 1
[name] => Loading (feat. Bad Boy Timz)
[popularity] => 64
[preview_url] => https://p.scdn.co/mp3-preview/7848a9f9ea879e6b1c6618508354e2559678aa8c?cid=756f211306ad4c9a934d07c5722790b5
[track_number] => 10
[type] => track
[uri] => spotify:track:558ULLj8yY2vT8XGtgY0q9
)
I would approach it like this:
$api = array (
'tracks' =>
array (
0 =>
array (
'album' =>
array (
'album_type' => 'album',
'artists' =>
array (
0 =>
array (
'external_urls' =>
array (
'spotify' => 'https://open.spotify.com/artist/4ovtyvs7j1jSmwhkBGHqSr',
),
'href' => 'https://api.spotify.com/v1/artists/4ovtyvs7j1jSmwhkBGHqSr',
'id' => '4ovtyvs7j1jSmwhkBGHqSr',
'name' => 'Olamide',
'type' => 'artist',
'uri' => 'spotify:artist:4ovtyvs7j1jSmwhkBGHqSr',
),
),
'external_urls' =>
array (
'spotify' => 'https://open.spotify.com/album/6fG2eFCgUmytQWL6umtsCh',
),
'href' => 'https://api.spotify.com/v1/albums/6fG2eFCgUmytQWL6umtsCh',
'id' => '6fG2eFCgUmytQWL6umtsCh',
'images' =>
array (
0 =>
array (
'height' => '640',
'url' => 'https://i.scdn.co/image/ab67616d0000b27387d20b9a27d5e14d74b5cb77',
'width' => '640',
),
1 =>
array (
'height' => '300',
'url' => 'https://i.scdn.co/image/ab67616d00001e0287d20b9a27d5e14d74b5cb77',
'width' => '300',
),
2 =>
array (
'height' => '64',
'url' => 'https://i.scdn.co/image/ab67616d0000485187d20b9a27d5e14d74b5cb77',
'width' => '64',
),
),
'name' => 'Carpe Diem',
'release_date' => '2020-10-07',
'release_date_precision' => 'day',
'total_tracks' => '12',
'type' => 'album',
'uri' => 'spotify:album:6fG2eFCgUmytQWL6umtsCh',
),
'artists' =>
array (
0 =>
array (
'external_urls' =>
array (
'spotify' => 'https://open.spotify.com/artist/4ovtyvs7j1jSmwhkBGHqSr',
),
'href' => 'https://api.spotify.com/v1/artists/4ovtyvs7j1jSmwhkBGHqSr',
'id' => '4ovtyvs7j1jSmwhkBGHqSr',
'name' => 'Olamide',
'type' => 'artist',
'uri' => 'spotify:artist:4ovtyvs7j1jSmwhkBGHqSr',
),
1 =>
array (
'external_urls' =>
array (
'spotify' => 'https://open.spotify.com/artist/5yOvAmpIR7hVxiS6Ls5DPO',
),
'href' => 'https://api.spotify.com/v1/artists/5yOvAmpIR7hVxiS6Ls5DPO',
'id' => '5yOvAmpIR7hVxiS6Ls5DPO',
'name' => 'Omah Lay',
'type' => 'artist',
'uri' => 'spotify:artist:5yOvAmpIR7hVxiS6Ls5DPO',
),
),
'disc_number' => '1',
'duration_ms' => '171764',
'explicit' => '1',
'external_ids' =>
array (
'isrc' => 'USUYG1330802',
),
'external_urls' =>
array (
'spotify' => 'https://open.spotify.com/track/5DS9LiyEdw2zY8bM6kjjgM',
),
'href' => 'https://api.spotify.com/v1/tracks/5DS9LiyEdw2zY8bM6kjjgM',
'id' => '5DS9LiyEdw2zY8bM6kjjgM
[is_local] => ',
'is_playable' => '1',
'name' => 'Infinity (feat. Omah Lay)',
'popularity' => '73',
'preview_url' => 'https://p.scdn.co/mp3-preview/5159fa17676fc96e32db13b7680f7497d5c2f74d?cid=756f211306ad4c9a934d07c5722790b5',
'track_number' => '3',
'type' => 'track',
'uri' => 'spotify:track:5DS9LiyEdw2zY8bM6kjjgM',
),
1 =>
array (
'album' =>
array (
'album_type' => 'album',
'artists' =>
array (
0 =>
array (
'external_urls' =>
array (
'spotify' => 'https://open.spotify.com/artist/4ovtyvs7j1jSmwhkBGHqSr',
),
'href' => 'https://api.spotify.com/v1/artists/4ovtyvs7j1jSmwhkBGHqSr',
'id' => '4ovtyvs7j1jSmwhkBGHqSr',
'name' => 'Olamide',
'type' => 'artist',
'uri' => 'spotify:artist:4ovtyvs7j1jSmwhkBGHqSr',
),
),
'external_urls' =>
array (
'spotify' => 'https://open.spotify.com/album/6fG2eFCgUmytQWL6umtsCh',
),
'href' => 'https://api.spotify.com/v1/albums/6fG2eFCgUmytQWL6umtsCh',
'id' => '6fG2eFCgUmytQWL6umtsCh',
'images' =>
array (
0 =>
array (
'height' => '640',
'url' => 'https://i.scdn.co/image/ab67616d0000b27387d20b9a27d5e14d74b5cb77',
'width' => '640',
),
1 =>
array (
'height' => '300',
'url' => 'https://i.scdn.co/image/ab67616d00001e0287d20b9a27d5e14d74b5cb77',
'width' => '300',
),
2 =>
array (
'height' => '64',
'url' => 'https://i.scdn.co/image/ab67616d0000485187d20b9a27d5e14d74b5cb77',
'width' => '64',
),
),
'name' => 'Carpe Diem',
'release_date' => '2020-10-07',
'release_date_precision' => 'day',
'total_tracks' => '12',
'type' => 'album',
'uri' => 'spotify:album:6fG2eFCgUmytQWL6umtsCh',
),
'artists' =>
array (
0 =>
array (
'external_urls' =>
array (
'spotify' => 'https://open.spotify.com/artist/4ovtyvs7j1jSmwhkBGHqSr',
),
'href' => 'https://api.spotify.com/v1/artists/4ovtyvs7j1jSmwhkBGHqSr',
'id' => '4ovtyvs7j1jSmwhkBGHqSr',
'name' => 'Olamide',
'type' => 'artist',
'uri' => 'spotify:artist:4ovtyvs7j1jSmwhkBGHqSr',
),
1 =>
array (
'external_urls' =>
array (
'spotify' => 'https://open.spotify.com/artist/68R39izwNAztATrXMOqkJS',
),
'href' => 'https://api.spotify.com/v1/artists/68R39izwNAztATrXMOqkJS',
'id' => '68R39izwNAztATrXMOqkJS',
'name' => 'Bad Boy Timz',
'type' => 'artist',
'uri' => 'spotify:artist:68R39izwNAztATrXMOqkJS',
),
),
'disc_number' => '1',
'duration_ms' => '194000',
'explicit' => '1',
'external_ids' =>
array (
'isrc' => 'USUYG1330809',
),
'external_urls' =>
array (
'spotify' => 'https://open.spotify.com/track/558ULLj8yY2vT8XGtgY0q9',
),
'href' => 'https://api.spotify.com/v1/tracks/558ULLj8yY2vT8XGtgY0q9',
'id' => '558ULLj8yY2vT8XGtgY0q9
[is_local] => ',
'is_playable' => '1',
'name' => 'Loading (feat. Bad Boy Timz)',
'popularity' => '64',
'preview_url' => 'https://p.scdn.co/mp3-preview/7848a9f9ea879e6b1c6618508354e2559678aa8c?cid=756f211306ad4c9a934d07c5722790b5',
'track_number' => '10',
'type' => 'track',
'uri' => 'spotify:track:558ULLj8yY2vT8XGtgY0q9',
),
),
);
$tracks = [];
foreach ($api['tracks'] as $track) {
$_track = [
'artists' => '',
'name' => '',
'album' => '',
'image' => ''
];
$artists = [];
foreach ($track['artists'] as $artist) {
$artists[] = $artist['name'];
}
$_track['artists'] = implode(', ', $artists);
$_track['name'] = $track['name'];
$_track['album'] = $track['album']['name'];
$_track['image'] = $track['album']['images'][2]['url'];
$tracks[] = $_track;
}
var_dump($tracks);
Results in:
array(2) {
[0]=>
array(4) {
["artists"]=>
string(17) "Olamide, Omah Lay"
["name"]=>
string(25) "Infinity (feat. Omah Lay)"
["album"]=>
string(10) "Carpe Diem"
["image"]=>
string(64) "https://i.scdn.co/image/ab67616d0000485187d20b9a27d5e14d74b5cb77"
}
[1]=>
array(4) {
["artists"]=>
string(21) "Olamide, Bad Boy Timz"
["name"]=>
string(28) "Loading (feat. Bad Boy Timz)"
["album"]=>
string(10) "Carpe Diem"
["image"]=>
string(64) "https://i.scdn.co/image/ab67616d0000485187d20b9a27d5e14d74b5cb77"
}
}
This is conveniently accomplished with array_walk_recursive. It doesn't matter at what depth or position your url key/value is, it will be found and iterated. As follows:
$urls = []; // For collecting URLs, passed in by reference:
array_walk_recursive($data, function($val, $key) use (&$urls) {
if($key === 'url') { // if $key is "url", add to $urls; ignore the rest.
$urls[] = $val;
}
});
Note that if you have multiple url keys at different depths/positions, they will all be added in. If you need to target a specific depth/position where multiple identical keys may exist, the solution would be a bit more complicated. In your use case this is not an issue, so I've kept it simple.
Also note that array_walk_recursive callback function is only called on the "leaves" or the final values of an array. As such, it will not be called on members that are arrays containing arrays. Non-final array members will simply be followed onward until "leaves" are found.
I have two arrays, $array1 and $array2. When combining the two arrays, the expected output is to combine both arrays based on their keys, and keep the array name as the key. I'm using array_merge_recursive($array1,$array2); which combines the two arrays, but keeping the array name as the key does not work with this.
$array1 = array(
'mobile' => array(
array('item' => 'apple','price' => 4),
array('item' => 'nokia','price' => 39),
array('item' => 'samsung','price' => 8)
),
'tv' => array(
array('item' => 'LG','price' => 39),
array( 'item' => 'max', 'price' => 8 ),
array('item' => 'diaken','price' => 3 )
)
) ;
$array2 = array(
'mobile' => array(
array('item' => 'HTC','price' => 4 ),
array('item' => 'OnePlus' ,'price' => 39),
array ('item' => 'Nexus','price' => 8 )
),
'tv' => array(
array('item' => 'LG','price' => 39),
array('item' => 'Panasonic','price' => 8 ),
array('item' => 'Toshiba' ,'price' => 3 )
)
);
The output should be:
array(
'mobile' => array(
'array1' => array(
'0' => array('item' => 'apple','price' => 4),
'1' => array('item' => 'nokia','price' => 39),
'2' => array('item' => 'samsung','price' => 8),
)
'array2' => array (
'0' => array('item' => 'HTC','price' => 4),
'1' => array('item' => 'OnePlus','price' => 39),
'2' => array('item' => 'Nexus','price' => 8)
)
),
'tv' => array(
'array1' => array(
'0' => array('item' => 'LG','price' => 39),
'1' => array('item' => 'max','price' => 8),
'2' => array('item' => 'diaken','price' => 3)
),
'array2' => array(
'0' => array('item' => 'LG','price' => 39),
'1' => array('item' => 'max','price' => 8),
'2' => array('item' => 'diaken','price' => 3)
)
)
)
I used array_merge_recursive($array1,$array2);, and instead of getting the above, I get the following:
Array
(
'mobile' => Array
(
Array('item' => 'apple','price' => 4),
Array('item' => 'nokia','price' => 39),
Array('item' => 'samsung','price' => 8),
Array('item' => 'HTC','price' => 4 ),
Array('item' => 'OnePlus' ,'price' => 39),
Array ('item' => 'Nexus','price' => 8 ),
)
'tv' => Array
(
Array('item' => 'LG','price' => 39),
Array( 'item' => 'max', 'price' => 8 ),
Array('item' => 'diaken','price' => 3 ),
Array ('item' => 'LG','price' => 39),
Array('item' => 'Panasonic','price' => 8 ),
Array('item' => 'Toshiba' ,'price' => 3 )
)
)
Whilst I don't know how you're going to automate the "discovery" of your array soruces, it should be as simple as this:
$array = array();
$array['mobile'] = array();
$array['mobile'][] = $array1['mobile'];
$array['mobile'][] = $array2['mobile'];
$array['tv'] = array();
$array['tv'][] = $array1['tv'];
$array['tv'][] = $array2['tv'];
// Using the array keys as the worker
$array = array();
foreach( array_keys( array_merge( $array1, $array2 ) ) as $key )
{
$array[$key] = array();
$array[$key][] = $array1[$key];
$array[$key][] = $array2[$key];
}
first array
$array1 = array
(
'mobile' => array
(
'0' => array
(
'item' => 'apple',
'price' => 4
),
'1' => array
(
'item' => 'nokia',
'price' => 39
),
'2' => array
(
'item' => 'samsung',
'price' => 8
),
),
'tv' => array
(
'0' => array
(
'item' => 'LG',
'price' => 39
),
'1' => array
(
'item' => 'max',
'price' => 8
),
'2' => array
(
'item' => 'diaken',
'price' => 3
),
)
) ;
second array
$array2 = array
(
'mobile' => array
(
'0' => array
(
'item' => 'HTC',
'price' => 4
),
'1' => array
(
'item' => 'OnePlus',
'price' => 39
),
'2' => array
(
'item' => 'Nexus',
'price' => 8
),
),
'tv' => array
(
'0' => array
(
'item' => 'LG',
'price' => 39
),
'1' => array
(
'item' => 'Panasonic',
'price' => 8
),
'2' => array
(
'item' => 'Toshiba',
'price' => 3
),
)
);
marge two array and print result
$array['mobile']['array1'] = $array1['mobile'];
$array['mobile']['array2'] = $array2['mobile'];
$array['tv']['array1'] = $array1['tv'];
$array['tv']['array2'] = $array2['tv'];
echo '<pre>';
print_r($array);
echo '</pre>';
output
Array
(
[mobile] => Array
(
[array1] => Array
(
[0] => Array
(
[item] => apple
[price] => 4
)
[1] => Array
(
[item] => nokia
[price] => 39
)
[2] => Array
(
[item] => samsung
[price] => 8
)
)
[array2] => Array
(
[0] => Array
(
[item] => HTC
[price] => 4
)
[1] => Array
(
[item] => OnePlus
[price] => 39
)
[2] => Array
(
[item] => Nexus
[price] => 8
)
)
)
[tv] => Array
(
[array1] => Array
(
[0] => Array
(
[item] => LG
[price] => 39
)
[1] => Array
(
[item] => max
[price] => 8
)
[2] => Array
(
[item] => diaken
[price] => 3
)
)
[array2] => Array
(
[0] => Array
(
[item] => LG
[price] => 39
)
[1] => Array
(
[item] => Panasonic
[price] => 8
)
[2] => Array
(
[item] => Toshiba
[price] => 3
)
)
)
)
i would like to do simply do following --
// loop through first array
$tempArray = [];
foreach($array1 as $key=>$object)
{
$tempArray[$key] = [];
array_push($tempArray[$key], $object);
array_push($tempArray[$key],$array2[$key]);
}
echo '<pre>';
print_r($tempArray);
echo '</pre>';
this will give you exact output what you want. Irrespective of how many keys exists in the array. You need to determine on which array loop should be imposed.
Please check below code if array1 and array2 are fixed as per your above comment
$array_keys = array_keys( array_merge( $array1, $array2));
$final_array = array();
foreach($array_keys as $akey)
{
if(array_key_exists($akey, $array1))
$final_array[$akey]['array1'] = $array1[$akey];
if(array_key_exists($akey, $array2))
$final_array[$akey]['array2'] = $array2[$akey];
}
echo "<pre>";
print_r($final_array);
echo "</pre>";
Input code:
$array1 = array(
'mobile' => array(
array('item' => 'apple','price' => 4),
array('item' => 'nokia','price' => 39),
array('item' => 'samsung','price' => 8)
),
'tv' => array(
array('item' => 'LG','price' => 39),
array( 'item' => 'max', 'price' => 8 ),
array('item' => 'diaken','price' => 3 )
)
) ;
$array2 = array (
'mobile' => array (
0 => array ('item' =>'HTC','price' => 4,),
1 => array ('item' =>'OnePlus','price' => 39,),
2 => array ('item' =>'Nexus','price' => 8,)
),
'tv' => array (
0 => array ('item' =>'LG','price' => 39,),
1 => array ('item' =>'Panasonic','price' => 8,),
2 => array ('item' =>'Toshiba','price' => 3)
)
);
o/p:
Array
(
[mobile] => Array
(
[array1] => Array
(
[0] => Array
(
[item] => apple
[price] => 4
)
[1] => Array
(
[item] => nokia
[price] => 39
)
[2] => Array
(
[item] => samsung
[price] => 8
)
)
[array2] => Array
(
[0] => Array
(
[item] => HTC
[price] => 4
)
[1] => Array
(
[item] => OnePlus
[price] => 39
)
[2] => Array
(
[item] => Nexus
[price] => 8
)
)
)
[tv] => Array
(
[array1] => Array
(
[0] => Array
(
[item] => LG
[price] => 39
)
[1] => Array
(
[item] => max
[price] => 8
)
[2] => Array
(
[item] => diaken
[price] => 3
)
)
[array2] => Array
(
[0] => Array
(
[item] => LG
[price] => 39
)
[1] => Array
(
[item] => Panasonic
[price] => 8
)
[2] => Array
(
[item] => Toshiba
[price] => 3
)
)
)
)
I need help organizing my inventory array. The structure is one big inventory array, with array of items inside. Per item array consists of the following:
item, item_group, item_no and array sold. sold consists of inner arrays with dates and quantity. Now, I'm having trouble organizing it for my needed output. I'll give you guys sample of input and output. So please do check and it's very much appreciated.
Sample part of my $inventory array
Array
(
[0] => Array
(
[item] => NK
[item_group] => 5
[sold] => Array
(
[0] => Array
(
[quantity] => 11
[date] => 2017-10-28
)
[1] => Array
(
[quantity] => 1
[date] => 2017-10-29
)
)
[item_no] => 1
)
[1] => Array
(
[item] => FL
[item_group] => 5
[sold] => Array
(
[0] => Array
(
[quantity] => 7
[date] => 2017-10-28
)
[1] => Array
(
[quantity] => 2
[date] => 2017-10-29
)
)
[item_no] => 2
)
[2] => Array
(
[item] => AD
[item_group] => 5
[sold] => Array
(
[0] => Array
(
[quantity] => 5
[date] => 2017-10-28
)
[1] => Array
(
[quantity] => 3
[date] => 2017-10-29
)
)
[item_no] => 3
)
[3] => Array
(
[item] => CV
[item_group] => 5
[sold] => Array
(
[0] => Array
(
[quantity] => 4
[date] => 2017-10-28
)
[1] => Array
(
[quantity] => 6
[date] => 2017-10-29
)
)
[item_no] => 4
)
[4] => Array
(
[item] => NB
[item_group] => 5
[sold] => Array
(
[0] => Array
(
[quantity] => 12
[date] => 2017-10-28
)
[1] => Array
(
[quantity] => 4
[date] => 2017-10-29
)
)
[item_no] => 5
)
[5] => Array
(
[item] => SP
[item_group] => 5
[sold] => Array
(
[0] => Array
(
[quantity] => 4
[date] => 2017-10-28
)
[1] => Array
(
[quantity] => 6
[date] => 2017-10-29
)
)
[item_no] => 6
)
[6] => Array
(
[item] => WB
[item_group] => 5
[sold] => Array
(
[0] => Array
(
[quantity] => 5
[date] => 2017-10-28
)
[1] => Array
(
[quantity] => 2
[date] => 2017-10-29
)
)
[item_no] => 7
)
[7] => Array
(
[item] => wny
[item_group] => 12
[sold] => Array
(
[0] => Array
(
[quantity] => 4
[date] => 2017-10-28
)
[1] => Array
(
[quantity] => 6
[date] => 2017-10-29
)
)
[item_no] => 8
)
[8] => Array
(
[item] => bs
[item_group] => 12
[sold] => Array
(
[0] => Array
(
[quantity] => 15
[date] => 2017-10-28
)
[1] => Array
(
[quantity] => 2
[date] => 2017-10-29
)
)
[item_no] => 9
)
[9] => Array
(
[item] => st
[item_group] => 12
[sold] => Array
(
[0] => Array
(
[quantity] => 16
[date] => 2017-10-29
)
)
[item_no] => 10
)
[10] => Array
(
[item] => ayhtdws
[item_group] => 12
[sold] => Array
(
[0] => Array
(
[quantity] => 2
[date] => 2017-10-29
)
)
[item_no] => 11
)
[11] => Array
(
[item] => sif
[item_group] => 12
[sold] => Array
(
[0] => Array
(
[quantity] => 3
[date] => 2017-10-29
)
)
[item_no] => 12
)
[12] => Array
(
[item] => bb
[item_group] => 12
[sold] => Array
(
[0] => Array
(
[quantity] => 6
[date] => 2017-10-29
)
)
[item_no] => 13
)
)
From there, what I want to display is like this. Grouped by date ascending. And each item => quantity sold
Array
(
[0] => Array
(
[date] => 2017-10-28
[NK] => 11
[FL] => 7
[AD] => 5
[CV] => 4
[NB] => 12
[SP] => 4
[WB] => 5
[wny] => 4
[bs] => 15
)
[1] => Array
(
[date] => 2017-10-29
[NK] => 1
[FL] => 2
[AD] => 3
[CV] => 6
[NB] => 4
[SP] => 6
[WB] => 2
[wny] => 6
[bs] => 2
[st] => 16
[ayhtdws] => 2
[sif] => 3
[bb] => 6
)
)
I've spent almost 3 days figuring this out and up to this writing, I was only able to make it this far
$result = array();
$dates = array();
foreach ($inventory as $key => $item) {
foreach ($item['sold'] as $k => $v) {
array_push($dates, $v['date']);
}
}
$dates = array_unique($dates);
foreach($dates as $key => $value) {
array_push($result, array('date' => $value));
}
foreach ($dates as $rkey => $rvalue) {
foreach ($inventory as $key => $item) {
foreach ($item['sold'] as $k => $v) {
if ($v['date'] = $result[$key]['date']) {
array_push($result[$key][$item['item']] = $v['quantity']);
}
}
}
}
return $result;
Which of course gives me this sad result
Array
(
[0] => Array
(
[date] => 2017-10-28
[NK] => 1
)
[1] => Array
(
[date] => 2017-10-29
[FL] => 2
)
)
And to make things worse, we have this rule about cyclomatic complexities that we should only have at most 3 loop/conditions and up to 3 nesting levels per loop/conditions. And the whole organizing should not have any user created functions.
Even if not following the rules, I wasn't able to figure it out for days. Sorry if problem is long. Please help :(
Update: var_export($inventory) output
array (
0 =>
array (
'item' => 'NK',
'item_group' => '5',
'sold' =>
array (
0 =>
array (
'quantity' => '11',
'date' => '2017-10-28',
),
1 =>
array (
'quantity' => '1',
'date' => '2017-10-29',
),
),
'item_no' => '1',
),
1 =>
array (
'item' => 'FL',
'item_group' => '5',
'sold' =>
array (
0 =>
array (
'quantity' => '7',
'date' => '2017-10-28',
),
1 =>
array (
'quantity' => '2',
'date' => '2017-10-29',
),
),
'item_no' => '2',
),
2 =>
array (
'item' => 'AD',
'item_group' => '5',
'sold' =>
array (
0 =>
array (
'quantity' => '5',
'date' => '2017-10-28',
),
1 =>
array (
'quantity' => '3',
'date' => '2017-10-29',
),
),
'item_no' => '3',
),
3 =>
array (
'item' => 'CV',
'item_group' => '5',
'sold' =>
array (
0 =>
array (
'quantity' => '4',
'date' => '2017-10-28',
),
1 =>
array (
'quantity' => '6',
'date' => '2017-10-29',
),
),
'item_no' => '4',
),
4 =>
array (
'item' => 'NB',
'item_group' => '5',
'sold' =>
array (
0 =>
array (
'quantity' => '12',
'date' => '2017-10-28',
),
1 =>
array (
'quantity' => '4',
'date' => '2017-10-29',
),
),
'item_no' => '5',
),
5 =>
array (
'item' => 'SP',
'item_group' => '5',
'sold' =>
array (
0 =>
array (
'quantity' => '4',
'date' => '2017-10-28',
),
1 =>
array (
'quantity' => '6',
'date' => '2017-10-29',
),
),
'item_no' => '6',
),
6 =>
array (
'item' => 'WB',
'item_group' => '5',
'sold' =>
array (
0 =>
array (
'quantity' => '5',
'date' => '2017-10-28',
),
1 =>
array (
'quantity' => '2',
'date' => '2017-10-29',
),
),
'item_no' => '7',
),
7 =>
array (
'item' => 'wny',
'item_group' => '12',
'sold' =>
array (
0 =>
array (
'quantity' => '4',
'date' => '2017-10-28',
),
1 =>
array (
'quantity' => '6',
'date' => '2017-10-29',
),
),
'item_no' => '8',
),
8 =>
array (
'item' => 'bs',
'item_group' => '12',
'sold' =>
array (
0 =>
array (
'quantity' => '15',
'date' => '2017-10-28',
),
1 =>
array (
'quantity' => '2',
'date' => '2017-10-29',
),
),
'item_no' => '9',
),
9 =>
array (
'item' => 'st',
'item_group' => '12',
'sold' =>
array (
0 =>
array (
'quantity' => '16',
'date' => '2017-10-29',
),
),
'item_no' => '10',
),
10 =>
array (
'item' => 'ayhtdws',
'item_group' => '12',
'sold' =>
array (
0 =>
array (
'quantity' => '2',
'date' => '2017-10-29',
),
),
'item_no' => '11',
),
11 =>
array (
'item' => 'sif',
'item_group' => '12',
'sold' =>
array (
0 =>
array (
'quantity' => '3',
'date' => '2017-10-29',
),
),
'item_no' => '12',
),
12 =>
array (
'item' => 'bb',
'item_group' => '12',
'sold' =>
array (
0 =>
array (
'quantity' => '6',
'date' => '2017-10-29',
),
),
'item_no' => '13',
),
)
I don't know if this is more or less the same as Erwin's code, but I wrote this code 13 hours ago and had to wait for the array.
Edit; I have tested Erwin's code and it seems we have close to matching code.
He makes one loop more to get the date in there but it's more or less the same.
I loop the array and the subarray sold.
I make the new array key the date example:
Echo $new['2017-10-28']['nk']; // 11
And if the date key is not set already I create it.
Once the loop is done I use array_values to remove the date keys making the array look like:
Echo $new[0]['nk']; // 11
The code:
$new =[];
Foreach($inventory as $sub){
Foreach($sub["sold"] as $sold){
If (!isset($new[$sold["date"]]["date"])) $new[$sold["date"]]["date"] = $sold["date"];
$new[$sold["date"]][$sub["item"]] = $sold["quantity"];
}
}
$new = array_values($new);
Var_dump($new);
https://3v4l.org/mGJSX
I've run through some tests and workarounds and come up with this solution. I've managed to do it by using ksort(), array_values()and array_key_exists(). I used the date first as an array key to contain all items sold on that date. Then, move it inside the array after gathering all items, then renumbered the array. Further explanation is given through code comments
// result array
$result = array();
// Loop for each item on inventory
foreach ($inventory as $inv) {
// Loop for each sold array
foreach ($inv['sold'] as $item) {
// date sold
$date = $item['date'];
// Check if date already exist in result array as key
// If not, Create new array with key equal to date and push to result array
if (!array_key_exists($date, $result)) {
$result[$date] = array();
}
// Add array of item => quantity to corresponding date array inside result array
$result[$date][$inv['item']] = $item['quantity'];
}
}
// From here you already have each item => quantity sold inside each date array
// e.g. $result = array( '2017-10-28' => array('NK' => '11', 'FL' => '7', ...) );
// Sort keys which are dates ascending
ksort($result);
// Loop to results and set
foreach ($result as $key => $value) {
$result[$key]['date'] = $key;
}
// Renumber Keys
$result = array_values($result);
// Print result
echo '<pre>';
print_r($result);
Output
Array
(
[0] => Array
(
[NK] => 11
[FL] => 7
[AD] => 5
[CV] => 4
[NB] => 12
[SP] => 4
[WB] => 5
[wny] => 4
[bs] => 15
[date] => 2017-10-28
)
[1] => Array
(
[NK] => 1
[FL] => 2
[AD] => 3
[CV] => 6
[NB] => 4
[SP] => 6
[WB] => 2
[wny] => 6
[bs] => 2
[st] => 16
[ayhtdws] => 2
[sif] => 3
[bb] => 6
[date] => 2017-10-29
)
)
I have an "tree" array like the following. This is a navigation. Now i want to remove all levels >= 3. So i only want to get an array with the first two levels. Is there a way to trim/shorten the array like that.
Do you have a hint for me what i can look for?
Array
(
[0] => Array
(
[name] => Home
[level] => 1
[sub] =>
)
[1] => Array
(
[name] => Products
[level] => 1
[sub] => Array
(
[56] => Array
(
[name] => Product 1
[level] => 2
[sub] => Array
(
[61] => Array
(
[name] => Product 1b
[target] =>
[level] => 3
[sub] =>
)
)
)
[57] => Array
(
[name] => Product 2
[level] => 2
[sub] =>
)
)
)
[2] => Array
(
[name] => Contact
[level] => 1
[sub] =>
)
[3] => Array
(
[name] => Something Else
[level] => 1
[sub] =>
)
)
$data = [
0 => ['name' => 'Home', 'level' => 1, 'sub' => []],
1 => [
'name' => 'Products',
'level' => 2,
'sub' => [
'56' => [
'name' => 'Product 1',
'level' => 2,
'sub' => [
'61' => [ 'name' => 'Product 1b', 'target' => '', 'level' => 3, 'sub' => ''],
],
],
'57' => ['name' => 'Product 2', 'level' => 2, 'sub' => '']
]
],
2 => ['name' => 'Contact', 'level' => 1, 'sub' => []],
3 => ['name' => 'Something Else', 'level' => 1, 'sub' => []]
];
function processArray(&$arr) {
foreach ($arr as $key => $array) {
if ($array['level'] >= 3) {
unset($arr[$key]);
}
if (!empty($arr[$key]['sub'])) {
processArray($arr[$key]['sub']);
}
}
}
processArray($data);
How can I sort an array with all children after their respective parents? I guess I'm trying to store a tree inside a one-dimensional array. I have tried to figure this out using usort, but I don't think it is the right tool for the job.
Example input array:
array (0 => array ( 'id' => '1', 'parent' => '0', ),
1 => array ( 'id' => '2', 'parent' => '1', ),
2 => array ( 'id' => '3', 'parent' => '0', ),
3 => array ( 'id' => '5', 'parent' => '0', ),
4 => array ( 'id' => '17', 'parent' => '3', ),
5 => array ( 'id' => '31', 'parent' => '2', ),
6 => array ( 'id' => '32', 'parent' => '2', ))
Example output:
Start by building an actual tree, then flatten that tree:
$array = array (0 => array ( 'id' => '1', 'parent' => '0', ),
1 => array ( 'id' => '2', 'parent' => '1', ),
2 => array ( 'id' => '3', 'parent' => '0', ),
3 => array ( 'id' => '5', 'parent' => '0', ),
4 => array ( 'id' => '17', 'parent' => '3', ),
5 => array ( 'id' => '31', 'parent' => '2', ),
6 => array ( 'id' => '32', 'parent' => '2', ));
/* Building a tree. We also save a map of references to avoid
searching the tree for nodes */
//Helper to create nodes
$tree_node = function($id, $parent) {
return array('id' => $id, 'parent' => $parent, 'children' => array());
};
$tree = $tree_node(0, null); //root node
$map = array(0 => &$tree);
foreach($array as $cur) {
$id = (int) $cur['id'];
$parentId = (int) $cur['parent'];
$map[$id] =& $map[$parentId]['children'][];
$map[$id] = $tree_node($id, $parentId);
}
//Now recursively flatten the tree:
function flatter($node) {
//Create an array element of the node
$array_element = array('id' => (string) $node['id'],
'parent' => (string) $node['parent']);
//Add all children after me
$result = array($array_element);
foreach($node['children'] as $child) {
$result = array_merge($result, flatter($child));
}
return $result;
}
$array = flatter($tree);
array_shift($array); //Remove the root node, which was only added as a helper
print_r($array);
<?php
/**
* #author Prasath A.R
* #copyright 2012
* #Date 2012-8-31 17:14
*/
$array = array (0 => array ( 'id' => '1', 'parent' => '0', ),
1 => array ( 'id' => '2', 'parent' => '1', ),
2 => array ( 'id' => '3', 'parent' => '0', ),
3 => array ( 'id' => '5', 'parent' => '0', ),
4 => array ( 'id' => '17', 'parent' => '3', ),
5 => array ( 'id' => '31', 'parent' => '2', ),
6 => array ( 'id' => '32', 'parent' => '2', ));
print_r($array);
echo "<br />";
for($i=0;$i<count($array);$i++)
{
for($j=$i;$j<count($array);$j++)
{
if($array[$i]['parent']>$array[$j]['parent'])
{
$temp=$array[$i];
$array[$i]=$array[$j];
$array[$j]=$temp;
}
}
}
echo "<h2>After Sorting</h2><br />";
print_r($array);
?>
The Answer will be:
Array
(
[0] => Array
(
[id] => 1
[parent] => 0
)
[1] => Array
(
[id] => 2
[parent] => 1
)
[2] => Array
(
[id] => 3
[parent] => 0
)
[3] => Array
(
[id] => 5
[parent] => 0
)
[4] => Array
(
[id] => 17
[parent] => 3
)
[5] => Array
(
[id] => 31
[parent] => 2
)
[6] => Array
(
[id] => 32
[parent] => 2
)
)
After Sorting
Array
(
[0] => Array
(
[id] => 1
[parent] => 0
)
[1] => Array
(
[id] => 3
[parent] => 0
)
[2] => Array
(
[id] => 5
[parent] => 0
)
[3] => Array
(
[id] => 2
[parent] => 1
)
[4] => Array
(
[id] => 31
[parent] => 2
)
[5] => Array
(
[id] => 32
[parent] => 2
)
[6] => Array
(
[id] => 17
[parent] => 3
)
)