Transforming multidimensional arrays - php

As a stepping stone towards building a bit of json from which to build dependent dropdown, I'd like to transform this array...
Array
(
[0] => Array
(
[id] => 4
[project_id] => 2289
[task] => Drawing
)
[1] => Array
(
[id] => 5
[project_id] => 2289
[task] => Surveying
)
[2] => Array
(
[id] => 6
[project_id] => 2289
[task] => Meeting
)
[3] => Array
(
[id] => 1
[project_id] => 2282
[task] => Folding
)
[4] => Array
(
[id] => 2
[project_id] => 2282
[task] => Printing
)
[5] => Array
(
[id] => 3
[project_id] => 2282
[task] => Cutting
)
)
..to something like this...
Array
(
[0] = Array
(
[project_id] => 2289
[task] => Array
(
[0] => Drawing
[1] => Surveying
[2] => Meeting
)
)
[1] = Array
(
[project_id] => 2282
[task] => Array
(
[0] => Folding
[1] => Printing
[2] => Cutting
)
)
)
Using...
$newArray = array();
foreach ($array as $row)
{
$newArray[$row['project_id']][] = $row['task'];
}
...I'm able to get this...
Array
(
[2289] => Array
(
[0] => Drawing
[1] => Surveying
[2] => Meeting
)
[2282] => Array
(
[0] => Folding
[1] => Printing
[2] => Cutting
)
)
... but I've forgotten how to include the associative keys in the result

You can modify your foreach simply using a index:
$newArray = array();
$index = array();
foreach ($array as $row)
{
$found = array_search( $row['project_id'], $index );
if( $found === False )
{
$found = array_push( $newArray, array( 'project_id' => $row['project_id'] ) )-1;
$index[$found] = $row['project_id'];
}
$newArray[ $found ]['task'][] = $row['task'];
}
eval.in demo
When a new project_id key is found, it is added to $index array, so — searching for it at next loop — I can retrieve the index of corresponding multi-dimensional array.

Just assign them as you would like, the project id in an index, and task continually pushing it there:
$newArray = array();
foreach ($array as $row) {
$newArray[$row['project_id']]['project_id'] = $row['project_id'];
$newArray[$row['project_id']]['task'][] = $row['task'];
}
$newArray = array_values($newArray); // reindex
// removes `$row['project_id']` on each group
Note: Just use array_values to reset the grouping key that you used in the project id grouping.

Related

Sorting php array by column in ascending order

Array
(
[content_type] => Array
(
[0] => story
[1] => delhi
[2] => tez
)
[type] => Array
(
[0] => video_id
[1] => subcategory
[2] => story_id
)
[fetch_id] => Array
(
[0] => 32
[1] => 32
[2] => 2
)
[order] => Array
(
[0] => 6
[1] => 4
[2] => 5
)
[label] => Array
(
[0] => dsfs fdsf dsf sdf
[1] => dfsdfs
[2] => sdfsdfsd
)
[link] => Array
(
[0] => fsd fsdf sdf
[1] => fsdfsdfdsf
[2] => fsdfdsfds
)
[record] => Array
(
[0] => 10
[1] => 8
[2] => 12
)
)
Above is the array I have to sort this array in the basis of order field and it should shorted all the fields accordingly like below example.
$arr['order'][0] = 4;
$arr['order'][1] = 5;
$arr['order'][2] = 6;
$arr['type'][0] = 'subcategory';
$arr['type'][1] = 'story_id';
$arr['type'][2] = 'video_id';
and so on.....
You can try this -
$new = array();
// Extract and get the keys as values
$order = array_flip($array['order']);
// sort them according to keys
ksort($order);
// loop through main array
foreach($array as $key => $sub_array) {
// loop through order
foreach ($order as $o) {
// store the new value according to order
$new[$key][] = $sub_array[$o];
}
}
Demo
Some lesser solution:
asort($array['order']);
foreach ($array as $key => $subArray) {
$array[$key] = array_replace($array['order'], $subArray);
}
For reset a key sequence you may just to use array_values().

How to merge two array where one array is dynamic nested values

I'm having two arrays like this
$whole_orders
Array
(
[2] => Array
(
[0] => Array
(
[id] => 3
[food_id] => 1
)
)
[1] => Array
(
[0] => Array
(
[id] => 2
[food_id] => 2
)
[1] => Array
(
[id] => 1
[food_id] => 1
)
)
)
And $array
Array
(
[2] => Array
(
[0] => Array
(
[count] => 1
[subtotal] => 103.42
[tax] => 18.42
)
)
[1] => Array
(
[0] => Array
(
[count] => 2
[subtotal] => 303.42
[tax] => 38.42
)
)
)
Here I'm having two arrays such as $whole_orders & $array from which I need to merge the $array values into the $whole_orders..
And the $whole_orders having nested values which are dynamic..
Finally My array should be like this..
Array
(
[2] => Array
(
[0] => Array
(
[id] => 3
[food_id] => 1
)
[1] => Array
(
[count] => 1
[subtotal] => 103.42
[tax] => 18.42
)
)
[1] => Array
(
[0] => Array
(
[id] => 2
[food_id] => 2
)
[1] => Array
(
[id] => 1
[food_id] => 1
)
[2] => Array
(
[count] => 2
[subtotal] => 303.42
[tax] => 38.42
)
)
)
It should append nested values of $whole_orders array's..
If you think that my title is not correct please change it..
Thanks in advance..
Use foreach and iterate your $array and assigned to $whole_orders
<?php
// if $array is always single dimension array
foreach($array as $array_key=>$array_val)
{
$whole_orders [$array_key][]=$val[0];
}
// or if $array is multi dimension array
foreach($array as $array_key=>$array_val)
{
foreach($array_val as $key=>$val)
{
$whole_orders [$array_key][]=$val;
}
}
?>
Just do this it will achieve you desire output ,but when if the count is same for both array
foreach($array as $arrayKey => $arrayValue){
foreach($arrayValue as $key => $value){
$whole_orders[$arrayKey][] = $value;
}
}
print_r($whole_orders);
You can try below approach..
$arr3 = array();
foreach($arr1 as $key => $value) :
$arr3[$key] = $value;
if(isset($arr2[$key])) :
foreach($arr2[$key] as $k=>$val) :
$arr3[$key][] = $val;
endforeach;
endif;
endforeach;
print_r($arr3);

count same categories from array and Store in new array with its count and category name

I have one array which I am getting from database query response.
Now I want to count same categories and print in option_name array.
I have tried it with different array functions but want get desire output.
I have one idea to take new array and push it with foreach loop but not much idea of how can i achieve using code. Please help me to solve it.
Array
(
[0] => Array
(
[CNC] => Array
(
[id] => 5
[category_id] => 68
)
[GVO] => Array
(
[option_name] => Actors
)
)
[1] => Array
(
[CNC] => Array
(
[id] => 11
[category_id] => 72
)
[GVO] => Array
(
[option_name] => Cricketers
)
)
[2] => Array
(
[CNC] => Array
(
[id] => 3
[category_id] => 72
)
[GVO] => Array
(
[option_name] => Cricketers
)
)
[3] => Array
(
[CNC] => Array
(
[id] => 4
[category_id] => 74
)
[GVO] => Array
(
[option_name] => Musician
)
)
[4] => Array
(
[CNC] => Array
(
[id] => 7
[category_id] => 76
)
[GVO] => Array
(
[option_name] => Directors
)
)
[5] => Array
(
[CNC] => Array
(
[id] => 6
[category_id] => 76
)
[GVO] => Array
(
[option_name] => Directors
)
)
)
Desire Output:
Array
(
[Actors] => 1
[Cricketers] => 2
[Musician] => 1
[Directors] => 2
)
Thanks in advance!
You simply need to loop through the array using foreach like as
$result = [];
foreach($arr as $k => $v){
if(isset($result[$v['GVO']['option_name']])){
$result[$v['GVO']['option_name']] += 1;
}else{
$result[$v['GVO']['option_name']] = 1;
}
}
print_R($result);
You can count the option_name values by incrementing a counter in an associative array where the key is the option_name:
$counts = [];
foreach($array as $v) {
if(!isset($counts[$v['GVO']['option_name']])) {
$counts[$v['GVO']['option_name']] = 0;
}
$counts[$v['GVO']['option_name']]++;
}
print_r($counts);
Try this:
$new_arr = array();
foreach(array_column($your_arr, 'option_name') as $value){
if(in_array($value, $new_array)){
$new_array[$value] = $new_array[$value]+1;
}else{
$new_array[$value] = 1;
}
}
Output
Array
(
[Actors] => 1
[Cricketers] => 2
[Musician] => 1
[Directors] => 2
)

array manipulation and rearranging

Here's my deal.
I have this array:
Array // called $data in my code
(
[0] => Array
(
[name] => quantity
[value] => 0
)
[1] => Array
(
[name] => var_id
[value] => 4
)
[2] => Array
(
[name] => quantity
[value] => 0
)
[3] => Array
(
[name] => var_id
[value] => 5
)
)
which I need it to be like:
Array // called $temp in my code
(
[0] => Array
(
[0] => Array
(
[name] => quantity
[value] => 0
)
[1] => Array
(
[name] => var_id
[value] => 4
)
)
[2] => Array
(
[0] => Array
(
[name] => quantity
[value] => 0
)
[1] => Array
(
[name] => var_id
[value] => 5
)
)
)
and I did it using this code I made:
$data = $_POST['data'];
$temp = array();
foreach($data as $key => $datum)
{
if($key%2 == 0)
{
$temp[$key] = array();
array_push($temp[$key], $datum, $data[$key+1]);
}
}
But I think that my code is some kinda stupid, specially if I have a huge data.
eventually what I want to do is just have each two indexes combined in one array, and I know that there should be something better than my code to do it, any suggestions?
Discover array_chunk()
$temp = array_chunk($data, 2);
$cnt = count($data);
$temp = array();
for ($i = 0; $i < $cnt; $i = $i + 2)
{
$temp[] = array($data[$i], $data[$i+1]);
}
Take a look at array_chunk.
<?php
$array = array(
array(1),
array(2),
array(3),
array(4),
);
print_r(
array_chunk($array, 2, false)
);
/*
Array
(
[0] => Array
(
[0] => Array
(
[0] => 1
)
[1] => Array
(
[0] => 2
)
)
[1] => Array
(
[0] => Array
(
[0] => 3
)
[1] => Array
(
[0] => 4
)
)
)
*/

how can i count an element if it appears more than once in the same array?

how can i count an element if it appears more than once in the same array?
I already tried with array_count_values, but it did not work, is it beacuse i got more than one key and value in my array?
This is my output from my array (restlist)
Array (
[0] => Array ( [restaurant_id] => 47523 [title] => cafe blabla)
[1] => Array ( [restaurant_id] => 32144 [title] => test5)
[2] => Array ( [restaurant_id] => 42154 [title] => blabla2 )
[3] => Array ( [restaurant_id] => 32144 [title] => test5)
[4] => Array ( [restaurant_id] => 42154 [title] => blabla2 )
)
I want it to count how many times the same element appears in my array and then add the counted value to my newly created 'key' called hits in the same array.
Array (
[0] => Array ( [restaurant_id] => 47523 [title] => cafe blabla [hits] => 1)
[1] => Array ( [restaurant_id] => 32144 [title] => test5 [hits] => 2)
[2] => Array ( [restaurant_id] => 42154 [title] => blabla2 [hits] => 2)
)
This is how i tried to do what i wanted.
foreach ($cooltransactions as $key)
{
$tempArrayOverRestaurants[]= $key['restaurant_id'];
}
$wordsRestaruants = array_count_values($tempArrayOverRestaurants);
arsort($wordsRestaruants);
foreach ($wordsRestaruants as $key1 => $value1)
{
$temprestaurantswithhits[] = array(
'restaurant_id' => $key1,
'hits' => $value1);
}
foreach ($restlistas $key)
{
foreach ($temprestaurantswithhits as $key1)
{
if($key['restaurant_id'] === $key1['restaurant_id'])
{
$nyspisestedsliste[] = array(
'restaurant_id' => $key['restaurant_id'],
'title' => $key['title'],
'hits' => $key1['hits']);
}
}
}
I know this is probably a noob way to do what i want but i am still new at php..I hope you can help
Just try with associative array:
$input = array( /* your input data*/ );
$output = array();
foreach ( $input as $item ) {
$id = $item['restaurant_id'];
if ( !isset($output[$id]) ) {
$output[$id] = $item;
$output[$id]['hits'] = 1;
} else {
$output[$id]['hits']++;
}
}
And if you want to reset keys, do:
$outputWithoutKeys = array_values($output);

Categories