How to combine associative array by indexes [duplicate] - php

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 10 months ago.
I have this associative array below:
Array
(
[0] => Array
(
[0] => Category
[1] => fruit
[2] => carbs
)
[1] => Array
(
[0] => Day 1 - Program
[1] => Eat banana
[2] => Eat bread
)
[2] => Array
(
[0] => Day 1 - record
[1] =>
[2] =>
)
)
each array index relates to the same index in the other arrays.
I need to now create 3 arrays by combining the index. The finished array would
look like this:
Array
(
[0] => Array
(
[0] => Category
[1] => Day 1 - Program
[2] => Day 1 - record
)
[1] => Array
(
[0] => fruit
[1] => Eat banana
[2] =>
)
[2] => Array
(
[0] => carbs
[1] => bread
[2] =>
)
)
The empty slots are where I know to put a textbox to record the data.
I've tried nesting for loops and other things but nothing is working.
How to combine array into a multidimensional array based on indexes?

$output = call_user_func_array(
'array_map',
array_merge(
array(NULL),
$input
)
);
Demo

You can achieve this with a nested loop. Loop through the sub-arrays first. On each iteration, loop through the elements in the sub-array, and add them into the result array. The important part here is what we use as the index for the $result array. $index will be the position of the array element in the sub-array. For example, Category would have an index of 0, so it would be pushed to $result[0][].
foreach ($array as $sub) {
foreach ($sub as $index => $val) {
$result[$index][] = $val;
}
}
print_r($result);
Demo

Here's a quick way - it essentially flips the keys. BTW, the first array you have is an indexed array, not an associative array.
$input = array(
array
(
"Category", "fruit", "carbs"
),
array
(
"Day 1 - Program","Eat banana","Eat bread"
),
array
(
"Day 1 - record", "", ""
)
);
foreach ($input as $key => $array){
foreach ($array as $k => $v){
$output[$k][$key] = $input[$key][$k];
}
}
print_r($output);

Related

Using array_flip() to return an array

I have an array:
$input = array(1,2,3,4,6,5,3,6)
and I want the key/value pairs to be flipped.
This can be done by using the array_flip() function.
$flipped = array_flip($input)
If in the original array has 2 or more same values (in this case number 6)how can I return it in an array?
array= ([1]=0,[2]=>1,[4]=>2,[6]=>array(3,6),[5]=>4,[3]=>5)
I tried to use array_count_values() but can't figure out how to do it?
You cannot do that using the array_flip() function. Probably you look for something like that:
<?php
function array_flip_and_collect($input) {
$output = [];
foreach ($input as $key=>$val) {
$output[$val][] = $key;
}
return $output;
}
$input = array(1,2,3,4,6,5,3,6);
print_r(array_flip_and_collect($input));
The output:
Array
(
[1] => Array
(
[0] => 0
)
[2] => Array
(
[0] => 1
)
[3] => Array
(
[0] => 2
[1] => 6
)
[4] => Array
(
[0] => 3
)
[6] => Array
(
[0] => 4
[1] => 7
)
[5] => Array
(
[0] => 5
)
)
Note that the output differs slightly from what you suggested in your question. That is by purpose because this appears more logical to me. If you really want that keys with only one element really are scalars and not arrays with one element, then you have to add an additional conversion step to the code.

How can I implode() only one column from a multidimensional array? [duplicate]

This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
I have array in following format:
Array
(
[sales] => Array
(
[0] => Array
(
[0] => 1
[1] => 6
)
[1] => Array
(
[0] => 2
[1] => 8
)
[2] => Array
(
[0] => 3
[1] => 25
)
[3] => Array
(
[0] => 4
[1] => 34
)
)
)
Using:
foreach ($data['sales'] as $k => $row) {
$list = implode(",",$row);
}
I get the following as output:
1,62,83,254,34
But I only need the second values from each subArray. The expected result needs to be:
6,8,25,34
How can I remove the first set of values?
Just grab the first column from your array with array_column(), so that you end up with an array, e.g.
Array (
[0] => 6
[1] => 8
[2] => 25
[3] => 34
)
And implode() it then as you already did, e.g.
echo implode(",", array_column($data["sales"], 1));
output:
6,8,25,34
I like array_column() but if you don't have PHP >= 5.5.0:
$list = implode(',', array_map(function($v) { return $v[1]; }, $data['sales']));
Or with the foreach:
foreach ($data['sales'] as $row) {
$list[] = $row[1];
}
$list = implode(',', $list);

running for loop on array without incremental index

I have this arbitrary multi dimensional array.
Array (
[0] => Array
(
[0] => 0
[1] => 1
[2] => 2
)
[5] => Array
(
[0] => 0
[1] => 1
[2] => 2
)
[10] => Array
(
[0] => 0
[1] => 1
[2] => 2
)
[15] => Array
(
[0] => 0
[1] => 1
[2] => 2
)
[1] => Array
(
[0] => 2
[1] => 1
[2] => 2
)
[2] => Array
(
[0] => 2
[1] => 1
[2] => 2
)
)
I wanna run a for loop to extract the data of each subarray.
But I cannot do a simple for loop because the index (0,5,10,15,1) is arbitrary.
Is there a way to run a for loop then skip the sub array if it is empty?
Thanks!
This will take $array and loop though it, echoing the keys.
You have an array in an array, you can place a foreach in a foreach:
// First we take the main array ($array) and loop though its values
foreach( $array as $main_key =>$sub_array){
echo $main_key.": <br />\n"; // echo the key, some extra html to format
// the values of the mainarray are arrays themselves, just loop again:
foreach($subarray as $sub_key =>$subvalue){
echo '- '.$subvalue."<br />\n";
}
}
There's a bit of a trap here if you foreach in a foreach:
foreach($array as $key =>$value){
foreach($value as $key=>$value){ /* ... */; }
}
This will create very weird results. The inner foreach uses the same parameter-names and will mess everything up.

Compare Two arrays array_diff_assoc() [duplicate]

This question already has answers here:
Compare 2-dimensional data sets based on a specified second level value
(9 answers)
Closed last year.
i need get value from 2 arrays...
First Array:
Array ( [0] => Array ( [id] => 1 [nombre_area] => biblioteca )
[1] => Array ( [id] => 2 [nombre_area] => enfermeria )
[2] => Array ( [id] => 3 [nombre_area] => talleres y laboratorios ) )
Second Array:
Array ( [0] => Array ( [0] => 1 [1] => biblioteca )
[1] => Array ( [0] => 3 [1] => talleres y laboratorios ) )
i need get the difference:
Array ( [0] => Array ( [id] => 2 [nombre_area] => enfermeria )
How can i do that ?
You are not operating on associative arrays at top level. You have two numeric arrays containing nested arrays. One of those contains associative arrays, the other one numeric arrays. First you could bring it in a normalized form, e.g. by $normalized = array_map( function($ar) { return array_values($ar); }, $array1 ); to the numeric form.
However, then you have two structures of the same form, but array_diff() won't perform a deep inspection. It will only compare a string representation of the elements at the first level. So you won't have another choice than recursively iterate the array, e.g. with help of the function array_walk_recursive().
You can try this one:
$array1 =Array (Array ( 'id' => 1, 'nombre_area' => 'biblioteca' ),Array ( 'id' => 2, 'nombre_area' => 'enfermeria' ),Array ( 'id' => 3 ,'nombre_area' => 'talleres y laboratorios' ) );
$array2 = Array (Array (1,'biblioteca' ), Array(3,'talleres y laboratorios' ));
$IDs = array_map(function($arr2){return $arr2[0];},$array2);
$result = array();
foreach($array1 as $arr1){
if(!in_array($arr1['id'],$IDs)) $result[] = $arr1; //compare id
}
print_r($result);

matching sub arrays on array and count them

i am having an array
Array
(
[1] => Array
(
[0] => 1
[1] => 3
)
[2] => Array
(
[0] => 1
[1] => 2
)
[3] => Array
(
[0] => 1
[1] => 3
)
)
and i need to find the common subarrays
In the above example array 1 and 3 have the common sub array
(
[0] => 1
[1] => 3
)
So the final array must be
Array
(
[1] => Array
(
[0] => 1
[1] => 3
)
[2] => Array
(
[0] => 1
[1] => 2
)
)
But i need to count the common values some how.
Any suggestion.
I wouldn't use this for production code, but here's a quick & somewhat clever way to do it:
$arrays = array(array(1,3), array(1,2), array(1,3)); // Your example data
$serialized = array_map('serialize', $arrays);
$counts = array_count_values($serialized);
foreach ($counts as $data => $count) {
echo "$count: " . print_r(unserialize($data), true);
}
Just compare each element of array with other assuming them as a linear array but use array_diff to compare each element. If they are different copy the element or array index into another array
To isolate unique rows, use the SORT_REGULAR flag with array_unique().
To acquire the number of duplicated rows, subtract the unique count from the initial count.
Code: (Demo)
$array = [[1, 3], [1, 2], [1, 3]];
$count = count($array);
$unique = array_unique($array, SORT_REGULAR);
echo "Number of duplicated rows: " . ($count - count($unique));

Categories