How to move an array into another? [duplicate] - php

This question already has answers here:
create array tree from array list [duplicate]
(9 answers)
Closed 9 years ago.
I have a multidimensional associative array "$nav_menus" looks like this:
Array
(
[0] => Array
(
[id] => 1
[menu_name] => Media
[parent_id] => 0
[submenus] => 1
)
[1] => Array
(
[id] => 2
[menu_name] => Movies
[parent_id] => 1
[submenus] => 1
)
[2] => Array
(
[id] => 3
[menu_name] => English Movies
[parent_id] => 2
[submenus] => 1
)
[3] => Array
(
[id] => 4
[menu_name] => Action
[parent_id] => 3
[submenus] => 1
)
)
What I'm trying to accomplish is to loop the array and whenever the value of the key ['parent_id'] doesn't equal 0 is to loop the array again and move this one into whatever menu the value of its ['id'] key equal that parent_id ... here is what I want $nav_menus to look like at the end
Array
(
[id] => 1
[menu_name] => Media
[parent_id] => 0
[submenus] => 1
[0] => Array
(
[id] => 2
[menu_name] => Movies
[parent_id] => 1
[submenus] => 1
[0] => Array
(
[id] => 3
[menu_name] =>English Movies
[parent_id] => 2
[submenus] => 1
[0] => Array
(
[id] => 4
[menu_name] => Action
[parent_id] => 3
[submenus] => 1
)
)
)
)
Here is what I was tried to accomplish it, but with no luck:
foreach($nav_menus as $k => $v){
if($v['parent_id'] !== 0){
$x = $v;
foreach($nav_menus as $key => $value){
if($value['id'] == $v['parent_id']){
unset($v);
array_push($value, $x);
break;
}
}
}
}
print_r($nav_menus);
It gives me the same original array without any change :( ... Any suggestions ?

Try this recursive function.
function array_new($arr1,$tot_count,$parent=0,$new_arr=array(),$global_count=0)
{
$count=0;
foreach($arr1 as $arr_res)
{
if($arr_res['parent_id']==$parent)
{
$new_arr['id'] = $arr_res['id'];
$new_arr['menu_name'] = $arr_res['menu_name'];
$new_arr['parent_id'] = $arr_res['parent_id'];
$new_arr['submenus'] = $arr_res['submenus'];
//DebugBreak();
if($global_count<$tot_count-1)
{ $global_count++;
$new_arr[$count] = array_new($arr1,$tot_count,$arr_res['id'],$new_arr,$global_count);
$count++;
}
}
}
return $new_arr;
}
'$arr_unformated' is your array which you have now.
$tot_count = count($arr_unformated);
$arrnew = array_new($arr_unformated,$tot_count);
And '$arrnew' is your desire array.

Related

Convert nested associative array to single array in php [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 10 months ago.
I have nested array with key & value pair. i want to convert it in single array.
/* This is current array */
Array
(
[id] => Array
(
[0] => 1
[1] => 2
)
[qty] => Array
(
[0] => 1
[1] => 1
)
[price] => Array
(
[0] => 364.41
[1] => 300
)
[amount] => Array
(
[0] => 364.41
[1] => 300
)
)
/*Now, I want this type of array*/
Array
(
[0] => Array
(
[id] => 1
[qty] => 1
[price] => 364.41
[amount] => 364.41
)
[1] => Array
(
[id] => 2
[qty] => 1
[price] => 300
[amount] => 300
)
)
I have tried array_walk and some other solutions but i could not find any proper solution
Thanks in advance
Main array is your nested array and Collection is the result you want
foreach($mainArray["id"] as $key => $value ){
$collection[$key] = ['id' => $value];
foreach(array_keys($mainArray) as $arrayKeysOfmainArray){
if(!array_key_exists($arrayKeysOfmainArray, $collection)){
$collection[$key][$arrayKeysOfmainArray] = $mainArray[$arrayKeysOfmainArray][$key];
}
}
}
print_r($collection);
$mainarray['id'] = Array(1,2,3);
$mainarray['qty'] = Array(1,1,4);
$mainarray['price'] = Array(364.41,300,500);
$mainarray['amount'] = Array(364.41,300,600);
$new = [];
foreach($mainarray as $key=> $singleArray){
if(count($singleArray) > 0){
foreach($singleArray as $childKey=> $value){
$new[$childKey][$key] = $value;
}
};
}`

How to add multiple values to an array in php

I want to create a new array using loop(foreach).
My array is looking like this :
$q_list = Array(
[0] => Array
(
[id] => 2
[subject_id] => 1
[question] => Question No One
[recordstatus] => 1
)
[1] => Array
(
[id] => 3
[subject_id] => 1
[question] => Question No Two
[recordstatus] => 1
)
[2] => Array
(
[id] => 4
[subject_id] => 1
[question] => Question No Three
[recordstatus] => 1
)
)
I have done like this but not working :
foreach ($q_list as $key => $q) {
$question[] = $q['question'];
$question[] = $q['subject_id'];
}
This will group your array on subject_id.
I use subject_id as the key in a multidimensional array that way it will just add the question arrays to the correct subarray.
foreach($q_list as $q){
$res[$q['subject_id']][] = $q;
}
var_dump($res);
https://3v4l.org/HnlYW

how to parse the following php array

I am trying to parse the following php array, somehow I am getting the result, but I couldn't get the expected output.
Array:
Array (
[0] => Array (
[countNos] => 2
[question_id] => 1
[question] => Is Service Best?
[rating] => 4
)
[1] => Array (
[countNos] => 1
[question_id] => 2
[question] => How much you benifitted?
[rating] => 5
)
[2] => Array (
[countNos] => 1
[question_id] => 2
[question] => How much you benifitted?
[rating] => 2
)
)
Current code:
foreach ($ratings as $rating) {
if (!in_array($rating['question_id'], $ratingArr)) {
$ratingArr[$rating['question_id']]['question_id'] = $rating['question_id'];
$ratingArr[$rating['question_id']]['question'] = $rating['question'];
}
for ($i = 5; $i >= 1; $i--) {
if (!in_array($rating['rating'], $ratingArr[$rating['question_id']]['stars'])) {
if ($i == $rating['rating']) {
$ratingArr[$rating['question_id']]['stars'][$i] = $rating['countNos'];
}
}
}
}
This is the output I am getting:
Notice: Undefined index: stars in C:\xampp\htdocs\mibs\module\Survey\src\Survey\Service\SurveyService.php on line 153
Warning: in_array() expects parameter 2 to be array, null given in C:\xampp\htdocs\mibs\module\Survey\src\Survey\Service\SurveyService.php on line 153
Array (
[1] => Array (
[question_id] => 1
[question] => Is Service Best?
[stars] => Array (
[4] => 2
)
)
[2] => Array (
[question_id] => 2
[question] => How much you benifitted?
[stars] => Array (
[5] => 1
[2] => 1
)
)
)
But I am expecting the following output:
Array(
[1] => Array(
[question_id] => 1
[question] => Is Service Best?
[stars] => Array(
[5] => 0
[4] => 2
[3] => 0
[2] => 0
[1] => 0
)
)
[2] => Array(
[question_id] => 2
[question] => How much you benifitted?
[stars] => Array(
[5] => 1
[4] => 0
[3] => 0
[2] => 1
[1] => 0
)
)
)
How can I parse this array, I am always having this type of issue, whenever I am parsing, how can I overcome this.
You're never creating a stars sub-array in $ratingArr when you initialize a new entry, that's causing the two warnings. To get all the zero entries, you should initialize this to an array of 5 zeroes. Then you don't need a loop to add the stars, you can just fill in the appropriate entry directly.
And you need to use array_key_exists, not in_array, to check whether there's already an entry for $rating['question_id'] in $ratingArr.
foreach ($ratings as $rating) {
if (!array_key_exists($rating['question_id'], $ratingArr)) {
$ratingArr[$rating['question_id']]['question_id'] = $rating['question_id'];
$ratingArr[$rating['question_id']]['question'] = $rating['question'];
$ratingArr[$rating['question_id']]['stars'] = array_fill(1, 5, 0);
}
$ratingArr[$rating['question_id']]['stars'][$rating['rating']] = $rating['countNos'];
}
Loop through your array and check if you already have a subArray with the question id in the result array. If not, initialize the subArray. And then just add the rating.
Code:
<?php
$result = [];
foreach($array as $v){
if(!isset($result[$v["question_id"]])){
$result[$v["question_id"]] = [
"question_id" => $v["question_id"],
"question" => $v["question"],
"stars" => array_fill_keys(range(5, 1), 0),
];
}
$result[$v["question_id"]]["stars"][$v["rating"]] += $v["countNos"]
}
?>

Copying a multi dimensional array of nodes into another array

I am looking to convert a multi dimensional array into another multidimensional array using a recursive function.
Source array :
Array
(
[1] => Array
(
[id] => 1
[source_name] => kk56ca1d0f2378f
[company_id] => 1
[lft] => 1
[rgt] => 18
[parent_id] => 0
[children] => Array
(
[2] => Array
(
[id] => 2
[source_name] => kk56ca1d17f3f63
[company_id] => 1
[lft] => 2
[rgt] => 3
[parent_id] => 1
[children] => Array
(
)
)
[3] => Array
(
[id] => 3
[source_name] => kk56ca1d1ebe975
[company_id] => 1
[lft] => 4
[rgt] => 13
[parent_id] => 1
[children] => Array
(
[6] => Array
(
[id] => 6
[source_name] => kk56ca1fc882ac0
[company_id] => 1
[lft] => 5
[rgt] => 10
[parent_id] => 3
[children] => Array
(
)
)
)
)
)
)
)
which I need to get into the format of
Array
(
[0] => Array
(
[id] => 1
[text] => kk56ca1d0f2378f
[parent_id] => 0
[nodes] => Array
(
[0] => Array
(
[id] => 2
[text] => kk56ca1d17f3f63
[parent_id] => 1
[nodes] => Array
(
)
)
[1] => Array
(
[id] => 3
[text] => kk56ca1d1ebe975
[parent_id] => 1
[nodes] => Array
(
[0] => Array
(
[id] => 6
[text] => kk56ca1fc882ac0
[parent_id] => 3
[nodes] => Array
(
)
)
[1] => Array
(
[id] => 15
[text] => kk
[parent_id] => 3
[nodes] => Array
(
)
)
)
)
)
)
)
I have been trying for hours and getting nowhere with this. Any help would be really appreciated.
The source array has associative indexes (though they are numbers) and the destination array has numerical indexes. Besides this, just need to remove a few indexes and change names of a few.
EDIT :
Specific changes :
change index name source_name to text
change index name children to nodes
unset indexes lft, rgt, company_id
I do not have much experience with recursion so I have trying fruitlessly.
This is what I could come up with :
// pass array of nodes
function convert_array($from){
// this is a node
if(isset($from['source_name']))
{
$temp = array();
$temp['id'] = $from['id'];
convert_array($from['children']);
}
// this is an array of nodes
else
{
foreach($from as $arr)
{
$ret = convert_array($arr);
print_r($ret);
}
}
}
But I am not able to understand what data to be returned and how the new array builds up from the return values.
Here the working function:
function convert_array( $array )
{
$retval = array();
foreach( $array as $row )
{
$child = array();
$child['id'] = $row['id'];
$child['text'] = $row['source_name'];
$child['parent_id'] = $row['parent_id'];
if( count( $row['children'] ) )
{ $child['nodes'] = convert_array( $row['children'] ); }
else
{ $child['nodes'] = array(); }
$retval[] = $child;
}
return $retval;
}
3v4l demo
I think it is self-explanatory, BTW: we init an empty array ($retval), then we perform a foreach loop through all array argument: for each element, we init a new array and we add it id, source_name as text and parent_id; if the children index has elements, we perform a recursive call to fill nodes array index, otherwise we set it to empty array.

PHP Grouping Array by Index [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 10 months ago.
I have a multidimensional array:
Array
(
[type] => Array
(
[0] => text
[1] => portfolio
[2] => slide
[3] => text
)
[grid] => Array
(
[0] => 3
[1] => 5
[2] => 3
[3] => 4
)
[title] => Array
(
[0] => title1
[3] => title2
)
[content] => Array
(
[0] => content1
[3] => content2
)
[item] => Array
(
[1] => 6
[2] => 7
)
[pagination] => Array
(
[1] => 8
)
[order] => Array
(
[1] => desc
[2] => asc
)
)
And want to group it by [type] key given in the array:
Array (
[0] => Array (
[type] => text
[grid] => 3
[title] => title1
[content] => content1
)
[1] => Array (
[type] => portfolio
[grid] => 5
[item] => 6
[pagination] => 1
[order] => desc
)
[2] => Array (
[type] => slide
[grid] => 3
[item] => 7
[order] => asc
)
[3] => Array (
[type] => text
[grid] => 4
[title] => title2
[content] => content2
)
Is there a way or PHP function to do array grouping like that?
This snippet achieves that:
$result = array();
foreach ($array as $key => $data) {
foreach ($data as $offset => $value) {
if (isset($result[$offset])) {
$result[$offset][$key] = $value;
} else {
$result[$offset] = array($key => $value);
}
}
}
Working DEMO
array_map() with null for the callback will do exactly what you want. However it will have number for the index instead of names.
If you write your own callback then you can return an array with the names you need.
Since apparently people want the actual code:
array_map(null, $type_array, $grid_array, $title_array, $content_array, $item_array);
It really is as simple as that. Most of the other answers are so large and unnecessary.
Note: This assumes a fixed number of arrays - if it's not fixed then this won't work, and then go with Florent's answer.
You can do it with this function:
$type_array = array('text', 'portfolio', 'slide', 'text');
$grid_array = array(3, 5, 3, 4);
$title_array = array(0 => 'title1', 3 => 'title2');
$content_array = array(0 => 'content1', 3 => 'content2');
$item_array = array(1 => 6, 2 => 7);
function group_arrays($type_array, $grid_array, $title_array, $content_array, $item_array) {
$temp_array = array();
for($i = 0; $i < count($type_array); $i++) {
$temp_array[$i] = array( 'type' => #$type_array[$i],
'grid' => #$grid_array[$i],
'title' => #$title_array[$i],
'content' => #$content_array[$i],
'item' => #$item_array[$i]);
}
return $temp_array;
}
print_r(group_arrays($type_array, $grid_array, $title_array, $content_array, $item_array));
Hope this helps!

Categories