Dynamic array inside an array using PHP - php

I am not sure if question title is ok or not!
I am trying to dynamically input array inside an array.
This is how it should be:
Example array:
$myArray = array (
'id' => 123,
'name' => 'Sufi',
'works' => array (
'show_work' => TRUE,
'number' => -1,
'order' => 'DESC',
/*i want this part to be dynamic */
array (
'title' => 'developer',
'experience' => '5 years',
'company' => 'ABC Inc.',
),
array (
'title' => 'CEO',
'experience' => '1 year',
'Company' => 'XYZ LLC.',
),
/*i want this part to be dynamic */
),
);
This is what I have:
//this array contains all works
$works = array(
array (
'title' => 'developer',
'experience' => '5 years',
'company' => 'ABC Inc.',
),
array (
'title' => 'CEO',
'experience' => '1 year',
'Company' => 'XYZ LLC.',
),
);
Now how can I pass this to $myArray dynamically?
My desired array format
Array
(
[id] => 123
[name] => sufi
[works] => Array
(
[show_work] => TRUE
[number] => -1
[order] => DESC
[0] => Array
(
[title] => developer
[experience] => 5 years
[company] => ABC Inc.
)
[1] => Array
(
[title] => CEO
[experience] => 1 year
[company] => XYZ LLC.
)
)
)

Hope I understood your question correctly:-
Try this:-
$myArray = array (
'id' => 123,
'name' => 'Sufi',
'works' => array (
'show_work' => true,
'number' => -1,
'order' => 'DESC'
)
);
$works = array(
array (
'title' => 'developer',
'experience' => '5 years',
'company' => 'ABC Inc.',
),
array (
'title' => 'CEO',
'experience' => '1 year',
'Company' => 'XYZ LLC.',
),
);
foreach ( $works as $work ) {
$myArray ['works'][] = $work;
}
Final Array will be:-
$myArray = array (
'id' => 123,
'name' => 'Sufi',
'works' => array (
'show_work' => TRUE,
'number' => -1
'order' => 'DESC',
[0] => array (
'title' => 'developer',
'experience' => '5 years',
'company' => 'ABC Inc.',
),
[1] => array (
'title' => 'CEO',
'experience' => '1 year',
'Company' => 'XYZ LLC.',
),
),
);

Thanks to those nice people, who tried to help me. I have solved it based on idea from #Ashutosh.
This is the solution:
foreach ( $works as $work ) {
$myArray ['works'][] = $work;
}

Related

How to sort an array by group of field value array in PHP

I want to sort collection of data by specific values like in sql ORDER BY VALUES() but in PHP. I have array like this
$array = array(
array('name' => 'Milk', 'type' => 'drink'),
array('name' => 'Coffee', 'type' => 'drink'),
array('name' => 'Orange', 'type' => 'fruit'),
array('name' => 'Computer', 'type' => 'other'),
array('name' => 'Water', 'type' => 'other'),
);
I want order data by type but not alphabetically, instead by specific values that I specify, order by type other, following by drink, following by fruit. So the result should be:
$array = array(
array('name' => 'Computer', 'type' => 'other'),
array('name' => 'Water', 'type' => 'other'),
array('name' => 'Milk', 'type' => 'drink'),
array('name' => 'Coffee', 'type' => 'drink'),
array('name' => 'Orange', 'type' => 'fruit'),
);
I tried usort but I have no idea how to compare with 2 values to achieve that. Thanks.
You can try this way also,
$array = array(
array('name' => 'Milk', 'type' => 'drink'),
array('name' => 'Coffee', 'type' => 'drink'),
array('name' => 'Orange', 'type' => 'fruit'),
array('name' => 'Computer', 'type' => 'other'),
array('name' => 'Water', 'type' => 'other'),
);
// array_flip turns 0 => 'other', 1 => 'drink', ... into 'other' => 0, 'drink' => 1, ...
$order=array_flip(array('other','drink','fruit'));
usort($array, function($x, $y) use($order) {
if (!isset($order[$x['type']], $order[$y['type']])) {
// none of the ids have order, so sort by bare type
return $x['type'] - $y['type'];
}
else if (!isset($order[$x['type']])) {
// x does not have order, put it last
return 1;
}
else if (!isset($order[$y['type']])) {
// y does not have order, put it last
return -1;
}
// both have types, use them
return $order[$x['type']] - $order[$y['type']];
});
echo "<pre>";
print_r($array);
output:-
Array
(
[0] => Array
(
[name] => Computer
[type] => other
)
[1] => Array
(
[name] => Water
[type] => other
)
[2] => Array
(
[name] => Milk
[type] => drink
)
[3] => Array
(
[name] => Coffee
[type] => drink
)
[4] => Array
(
[name] => Orange
[type] => fruit
)
)
Yes, you can use usort like:
$array = array(
array('name' => 'Milk', 'type' => 'drink'),
array('name' => 'Coffee', 'type' => 'drink'),
array('name' => 'Orange', 'type' => 'fruit'),
array('name' => 'Computer', 'type' => 'other'),
array('name' => 'Water', 'type' => 'other'),
);
usort($array,function($a,$b){
//Define the order
$order = array( 'other' => 0 , 'drink' => 1, 'fruit' => 2 );
//Compare the order
return $order[ $a[ 'type' ] ] > $order[ $b[ 'type' ] ];
});
echo "<pre>";
print_r( $array );
echo "</pre>";
This will result to:
Array
(
[0] => Array
(
[name] => Computer
[type] => other
)
[1] => Array
(
[name] => Water
[type] => other
)
[2] => Array
(
[name] => Milk
[type] => drink
)
[3] => Array
(
[name] => Coffee
[type] => drink
)
[4] => Array
(
[name] => Orange
[type] => fruit
)
)
If in case some of the types are on the array, you can do this to make sure that the undefined will be put on the last.
usort($array,function($a,$b){
$order = array( 'other' => 0 , 'drink' => 1, 'fruit' => 2 );
$aOrder = isset( $order[ $a[ 'type' ] ] ) ? $order[ $a[ 'type' ] ] : 1000000000000;
$bOrder = isset( $order[ $b[ 'type' ] ] ) ? $order[ $b[ 'type' ] ] : 1000000000000;
return $aOrder > $bOrder;
});

Mongodb Search from Collection

I need to Search collection in mongodb having
'food_name' => 'fish'
and
'room_features' =>
array (
0 => 'Shower',
1 => 'Hairdryer',
),
I tried the following code. But the result is not-correct. I think multiple $eq is not allowed (same index in array).
array (
'$and' =>
array (
array (
'food' =>
array (
'$elemMatch' =>
array (
'food_name' =>
array (
'$eq' => 'fish',
),
),
),
),
array (
'room' =>
array (
'$elemMatch' =>
array (
'room_features' =>
array (
'$elemMatch' =>
array (
'$eq' => 'Shower'
'$eq' => 'Hairdryer'
),
),
'roomrate' =>
array (
'$eq' => new MongoInt32(2500),
),
),
),
),
),
)
Here is the document I need to search.
array (
'_id' => new MongoId("59670aca7fafd8342e3c9869"),
'subcat_name' => 'Test',
'place' => '',
'description' => '',
'created_date' => '1499970060',
'created_by' => 'Admin',
'openingtime' => '',
'closingtime' => '',
'hotel_class_id' => '594245f67fafd87e243c986a',
'hotel_type_id' => '594244177fafd884563c9869',
'latitude' => '0',
'longitude' => '0',
'dist_id' => '5911966a7fafd8c83c3c986a',
'cat_id' => '58fb230e7fafd883183c986d',
'featured' => '0',
'visited' => new MongoInt64(5),
'subcat_slug' => 'test-trivandrum-1',
'image' => NULL,
'food' =>
array (
0 =>
array (
'food_id' => '149992634012642164',
'region_id' => '5944ba947fafd883333c9869',
'food_name' => 'fish',
'type' => 'veg',
'rate' => '100',
),
1 =>
array (
'food_id' => '14999366891994980639',
'region_id' => '595c75c17fafd835173c986c',
'food_name' => 'curry',
'type' => 'veg',
'rate' => '1000',
),
),
'room' =>
array (
0 =>
array (
'room_id' => '14999346791721342880',
'roomtype' => 'DELUXE KING ROOM1',
'roomrate' => new MongoInt64(2500),
'image' => 'beach_icon33.png',
'room_features' =>
array (
0 => 'Shower',
1 => 'Hairdryer',
),
),
1 =>
array (
'room_id' => '14999346901389554873',
'roomtype' => 'DELUXE KING ROOM new',
'roomrate' => new MongoInt64(4000),
'image' => 'beach_icon34.png',
'room_features' =>
array (
0 => 'Shower',
1 => 'Bathrobe',
),
),
),
)
Please Give me an alternate way to search multiple item from array.
Thanks in advance.
I think if you want to query list you can add the list in query,
try this
{
"food" : {
"$elemMatch": {
"food_name" : "fish"
}
},
"room" : {
"$elemMatch": {
"room_features" : ["Shower", "Hairdryer"]
}
},
}
Hope this help.

php, 3 array to one array merge alternative

I have 3 arrays. These inter-related. I want to combine these statements.
<?php
$post = array(
array (
'id' => 1,
'title' => 'Title 1',
'content' => 'Content 1'
),
array (
'id' => 2,
'title' => 'Title 2',
'content' => 'Content 2'
),
array (
'id' => 3,
'title' => 'Title 3',
'content' => 'Content 3'
),
);
$user = array(
array (
'id' => 1,
'name' => 'Mark'
),
array (
'id' => 2,
'name' => 'Selena'
)
);
$post_user = array(
array (
'id' => 1,
'post_id' => 1,
'user_id' => 1
),
array (
'id' => 2,
'post_id' => 2,
'user_id' => 1
),
array (
'id' => 3,
'post_id' => 3,
'user_id' => 2
),
);
$merge = array();
foreach($posts_user as $data){
foreach ($posts as $post){
if($data['post_id'] == $post['id'] ){
foreach ($users as $user){
if($data['user_id'] == $user['id']){
$post['user'] = $user;
$merge['post'][] = $post;
}
}
}
}
}
print_r($merge);
I want to be as follows. How can I do it?
I want results.
$merge = array(
array (
'id' => 1,
'title' => 'Title 1',
'content' => 'Content 1',
'user' => array (
'id' => '1',
'name' => 'Mark'
),
),
array (
'id' => 2,
'title' => 'Title 2',
'content' => 'Content 2',
'user' => array (
'id' => '1',
'name' => 'Mark'
),
),
array (
'id' => 3,
'title' => 'Title 3',
'content' => 'Content 3',
'user' => array (
'id' => '2',
'name' => 'Selena'
),
),
);
Is there another alternative? For example; How do I do with them?
array_walk_recursive(), ArrayIterator(), RecursiveArrayIterator()
I tried to do.
<?php
$post = array(
array (
'id' => 1,
'title' => 'Title 1',
'content' => 'Content 1'
),
array (
'id' => 2,
'title' => 'Title 2',
'content' => 'Content 2'
),
array (
'id' => 3,
'title' => 'Title 3',
'content' => 'Content 3'
),
);
$user = array(
array (
'id' => 1,
'name' => 'Mark'
),
array (
'id' => 2,
'name' => 'Selena'
)
);
$post_user = array(
array (
'id' => 1,
'post_id' => 1,
'user_id' => 1
),
array (
'id' => 2,
'post_id' => 2,
'user_id' => 1
),
array (
'id' => 3,
'post_id' => 3,
'user_id' => 2
),
);
$newuser = array();
foreach($post_user as $data){
foreach ($user as $users){
if($data['user_id'] == $users['id']){
$newuser[] = $users;
}
}
}
$mi = new MultipleIterator(MultipleIterator::MIT_NEED_ALL|MultipleIterator::MIT_KEYS_ASSOC);
$mi->attachIterator(new ArrayIterator($post),1);
$mi->attachIterator(new ArrayIterator($newuser),'user');
$newArray = array();
foreach($mi as $details) {
$newArray[] = $details;
}
print_r($newArray);
Results
Array
(
[0] => Array
(
[1] => Array
(
[id] => 1
[title] => Title 1
[content] => Content 1
)
[user] => Array
(
[id] => 1
[name] => Mark
)
)
[1] => Array
(
[1] => Array
(
[id] => 2
[title] => Title 2
[content] => Content 2
)
[user] => Array
(
[id] => 1
[name] => Mark
)
)
[2] => Array
(
[1] => Array
(
[id] => 3
[title] => Title 3
[content] => Content 3
)
[user] => Array
(
[id] => 2
[name] => Selena
)
)
)

PHP - generate multi-dimentional array

This is my array:
$arr = array(
0 => array(
'title' => 'test1',
'count' => 4,
'month' => 'jan-2015'
),
1 => array(
'title' => 'test2',
'count' => 10,
'month' => 'jan-2015'
),
2 => array(
'title' => 'test3',
'count' => 14,
'month' => 'jun-2015'
),
3 => array(
'title' => 'test4',
'count' => 45,
'month' => 'july-2015'
),
);
I've to convert this array into multi-dimentional array as below:
$arr = array(
'jan-2015' => array(
0 => array(
'title' => 'test1',
'count' => 4,
),
1 => array(
'title' => 'test2',
'count' => 10,
),
),
'jun-2015' => array(
0 => array(
'title' => 'test3',
'count' => 14,
),
),
'july-2015' => array(
0 => array(
'title' => 'test4',
'count' => 45,
),
),
);
I've tried to make it as expected but unfortunately i can't make this.
Is any other solutions for this?
According to your data structure :
$arr = array(
0 => array(
'title' => 'test1',
'count' => 4,
'month' => 'jan-2015'
),
1 => array(
'title' => 'test2',
'count' => 10,
'month' => 'jan-2015'
),
2 => array(
'title' => 'test3',
'count' => 14,
'month' => 'jun-2015'
),
3 => array(
'title' => 'test4',
'count' => 45,
'month' => 'july-2015'
),
);
try this:
$newArray = array();
foreach($arr as $key => $val) {
$newArray[$val['month']][] = $val;
}
echo '<pre>'.print_r($newArray,1).'</pre>';
Output:
Array
(
[jan-2015] => Array
(
[0] => Array
(
[title] => test1
[count] => 4
[month] => jan-2015
)
[1] => Array
(
[title] => test2
[count] => 10
[month] => jan-2015
)
)
[jun-2015] => Array
(
[0] => Array
(
[title] => test3
[count] => 14
[month] => jun-2015
)
)
[july-2015] => Array
(
[0] => Array
(
[title] => test4
[count] => 45
[month] => july-2015
)
)
)
You could use this function:
function transform($input) {
// Extract months, and use them as keys, with value set to empty array
// The array_fill_keys also removes duilicates
$output = array_fill_keys(array_column($input, 'month'), array());
foreach ($input as $element) {
$copy = $element;
// remove the month key
unset($copy["month"]);
// assign this to the month key in the output
$output[$element["month"]][] = $copy;
}
return $output;
}
Call it like this:
$arr = array(
0 => array(
'title' => 'test1',
'count' => 4,
'month' => 'jan-2015'
),
1 => array(
'title' => 'test2',
'count' => 10,
'month' => 'jan-2015'
),
2 => array(
'title' => 'test3',
'count' => 14,
'month' => 'jun-2015'
),
3 => array(
'title' => 'test4',
'count' => 45,
'month' => 'july-2015'
),
);
print_r (transform($arr));
Output:
Array
(
[jan-2015] => Array
(
[0] => Array
(
[title] => test1
[count] => 4
)
[1] => Array
(
[title] => test2
[count] => 10
)
)
[jun-2015] => Array
(
[0] => Array
(
[title] => test3
[count] => 14
)
)
[july-2015] => Array
(
[0] => Array
(
[title] => test4
[count] => 45
)
)
)
By using answer of #Girish Patidar, You can achieve this by:
$outputArr = array();
$to_skip = array();
foreach($arr as $row){
$to_skip = $row;
unset($to_skip['month']);
$outputArr[$row['month']][] = $to_skip;
}
echo "<pre>";
print_r($outputArr);
die;
There could many way to do this. Please try this one if it works for you
<?php
$newArr=NULL;
foreach($arr as $array)
{
$temp=NULL;
$temp['title']=$array['title'];
$temp['count']=$array['count'];
$newArr[$array['month']][]=$temp;
}
var_dump($newArr);
?>

PHP merge associative arrays by replacing same keys and adding new

I have an array of variable size structured like this (categories is only one of the keys inside data):
print_r($json[123]["data"]["categories"]);
array(
array(
'id' => '2',
'description' => 'Single-player'
),
array(
'id' => '1',
'description' => 'Multi-player'
),
array(
'id' => '9',
'description' => 'Co-op'
),
array(
'id' => '22',
'description' => 'Steam Achievements'
),
array(
'id' => '28',
'description' => 'Full controller support'
)
)
print_r($json[456]["data"]["categories"]);
array(
array(
'id' => '21',
'description' => 'Downloadable Content'
),
array(
'id' => '1',
'description' => 'Multi-player'
)
)
Now, I want to merge these sub-arrays (they can be in variable number) and have all keys added and replaced. I've tried array_merge but it replaces the keys without adding new ones.
In this case I need to obtain this array:
print_r($merged["data"]["categories"]);
array(
array(
'id' => '2',
'description' => 'Single-player'
),
array(
'id' => '1',
'description' => 'Multi-player'
),
array(
'id' => '9',
'description' => 'Co-op'
),
array(
'id' => '22',
'description' => 'Steam Achievements'
),
array(
'id' => '28',
'description' => 'Full controller support'
),
array(
'id' => '21',
'description' => 'Downloadable Content'
)
)
Any help?
Edit:
I think I didn't expressed myself well enough. $json[$id]["data"] has multiple keys I want to merge (categories is just an example). Also the number of $json[$id] keys is variable
Edit2:
The arrays can have duplicate values, and the depth of the keys can be variable. I need to get something like array_merge_recursive() but with same values replaced.
Edit3:
This is the current array. http://pastebin.com/7x7KaAVM I need to merge all keys that have sub-arrays
Try below code:
$json = array(
'123' => array('data' => array('categories' => array(
array(
'id' => '2',
'description' => 'Single-player'
),
array(
'id' => '1',
'description' => 'Multi-player'
),
array(
'id' => '9',
'description' => 'Co-op'
),
array(
'id' => '22',
'description' => 'Steam Achievements'
),
array(
'id' => '28',
'description' => 'Full controller support'
)
))
),
'456' => array('data' => array('categories' => array(
array(
'id' => '21',
'description' => 'Downloadable Content'
)
))
),
);
//print_r($json);
$merged = array();
foreach($json as $j1)
{
foreach($j1 as $j2)
{
foreach($j2 as $key => $j3)
{
foreach($j3 as $j4)
{
$merged[$key][] = $j4;
}
}
}
}
print_r($merged);
Result:
Array
(
[categories] => Array
(
[0] => Array
(
[id] => 2
[description] => Single-player
)
[1] => Array
(
[id] => 1
[description] => Multi-player
)
[2] => Array
(
[id] => 9
[description] => Co-op
)
[3] => Array
(
[id] => 22
[description] => Steam Achievements
)
[4] => Array
(
[id] => 28
[description] => Full controller support
)
[5] => Array
(
[id] => 21
[description] => Downloadable Content
)
)
)
Demo:
http://3v4l.org/X61bE#v430
Try this . To generalize I have added some more arrays.
<?php
$merged_array = array();
$final_array = array();
$json[123]["data"]["categories"] = array(
array(
'id' => '2',
'description' => 'Single-player'
),
array(
'id' => '1',
'description' => 'Multi-player'
),
array(
'id' => '9',
'description' => 'Co-op'
),
array(
'id' => '22',
'description' => 'Steam Achievements'
),
array(
'id' => '28',
'description' => 'Full controller support'
)
);
$json[456]["data"]["categories"] = array(
array(
'id' => '21',
'description' => 'Downloadable Content'
)
);
$json[786]["data"]["categories"] = array(
array(
'id' => '31',
'description' => 'Downloadable Content'
)
);
$json[058]["data"]["categories"] = array(
array(
'id' => '41',
'description' => 'Downloadable Content'
)
);
foreach($json as $key=>$value){
array_push($merged_array,$json[$key]["data"]["categories"]);
}
foreach($merged_array as $value){
foreach($value as $val){
array_push($final_array,$val);
}
}
print_r($final_array);
?>
RESULT
Array
(
[0] => Array
(
[id] => 2
[description] => Single-player
)
[1] => Array
(
[id] => 1
[description] => Multi-player
)
[2] => Array
(
[id] => 9
[description] => Co-op
)
[3] => Array
(
[id] => 22
[description] => Steam Achievements
)
[4] => Array
(
[id] => 28
[description] => Full controller support
)
[5] => Array
(
[id] => 21
[description] => Downloadable Content
)
[6] => Array
(
[id] => 31
[description] => Downloadable Content
)
[7] => Array
(
[id] => 41
[description] => Downloadable Content
)
)

Categories