Consolidate an array in PHP? - php

I have an array that looks like the following:
Array (
[0] => Array
(
[id] => 10
[value] => 5
)
[1] => Array
(
[id] => 10
[value] => 1
)
[2] => Array
(
[id] => 11
[value] => 1
)
[3] => Array
(
[id] => 11
[value] => 1
)
)
How can I consolidated the array by id? The resulting array I'm looking for would be something like:
Array (
[0] => Array
(
[id] => 10
[value] => 6
)
[1] => Array
(
[id] => 11
[value] => 2
)
)

This is not a very efficient structure. Have you considered consolidating it in this form?
array
(
10 => 6,
11 => 2,
);
That would allow fast key lookup on ID.
TO consolidate your first array into that form, just do this:
$array2 = array();
foreach($array1 as $row)
{
if(isset($array2[$row['id']]))
$array2[$row['id']] += $row['value'];
else
$array2[$row['id']] = $row['value'];
}
Which would give you an array in the form of:
$array2 = array
(
10 => 6,
11 => 2,
);
If you really need it in your requested form, one more processing loop will get it there...
$array3 = array();
foreach($array2 as $id => $value)
{
$array3[] = array('id' => $id, 'value' => $value);
}
So, there you go!
And more compact:
$array2 = array();
foreach($array1 as $row)
$array2[$row['id']] = (isset($array2[$row['id']]) ? $array2[$row['id']] : 0) + $row['value'];
$array3 = array();
foreach($array2 as $id => $value)
$array3[] = array('id' => $id, 'value' => $value);

Related

How to loop multi dimensional array to get values

I have this multi-dimensional array and I'm trying to convert it into array given below
Array
(
[id] => Array
(
[0] => 1
[1] => 3
)
[team_id] => Array
(
[0] => 654868479
[1] => 463733228
)
[seed] => Array
(
[0] => 1
[1] => 2
)
)
I want following result
Array
(
[0] => Array
(
[id] => 1
[team_id] => 654868479
[seed] => 1
)
[1] => Array
(
[id] => 3
[team_id] => 463733228
[seed] => 3
)
)
Here is what I have achieved so far. I actually want $seeded[] array is the same format as it is required to submit update_batch. Which will ultimately update database records.
$seeds = $this->input->post();
$i=0;
foreach ($seeds as $key => $value){
if(!empty($key) && !empty($value)){
for($i=0; $i=5; $i++) {
$seeded[] = array(
'id' => (id go here),
'tournament_id' => $tournament_id,
'stage_id' => $stage_id,
'seed_id' => (seed go here),
'team_name' => (team_id go here),
);
}
$this->db->update_batch('tournament_seed', $seeded, 'id');
}
}
Iterate the array and convert it using below code.
$seeded= array();
for($i =0; $i < count($seeds['id']); $i++){
$tempArr['id'] = $seeds['id'][$i];
$tempArr['team_id'] = $seeds['team_id'][$i];
$tempArr['seed'] = $seeds['seed'][$i];
$seeded[] = $tempArr;
}
I've written a function that will allow you to transform any array of similar structure to what you have above, to an array of the form you are looking for.
You can build your array in this way:
$arr = [
'id' => [1, 3],
'team_id' => [654868479, 463733228],
'seed' => [1, 2],
];
function array_flatten($arr) {
$res = [];
foreach($arr as $id => $valuesArray) {
foreach($valuesArray as $index => $value)
$res[$index][$id] = $value;
}
return $res;
}
print_r(array_flatten($arr));
Hope this helps,

Change key on array_chunk php

I have array based POST like this :
Array
(
[condition] => Array
(
[0] => 1
)
[container] =>
[cleaning] => Y
[owner] => Eagletainer
[last_cargo] => 1
[vessel] =>
[insulation] => 1
[tare] =>
[gross] =>
[capacity] =>
[unit_type] => IMO 1
[date_of_manu] =>
[name_manu] =>
[last25] =>
[cert25] =>
[last5] =>
[cert5] =>
[list2_item_0] => 1
[list2_kondisi_0] => 9
[list3_item_0] => 15
[list3_kondisi_0] => 3
[comments] =>
)
My case is, I want to chunk a lot of those element array into another array for insert_batch in my database.
This is the php code to chunk those array:
public function get_partition($array, $p, $c) {
$partition = array_slice($array, $p);
array_pop($partition);
return $chunk = array_chunk($partition, $c);
}
Now, use it,
$detail = $this->get_partition($this->input->post(), 17, 2);
The result is :
Array
(
[0] => Array
(
[0] => 1
[1] => 9
)
[1] => Array
(
[0] => 15
[1] => 3
)
)
My question in, how to change the key [0] and [1] into another key like [ID] and [CODE_DAMAGE]
I want them looked like this :
Array
(
[0] => Array
(
[ID] => 1
[CODE_DAMAGE] => 9
)
[1] => Array
(
[ID] => 15
[CODE_DAMAGE] => 3
)
)
Re-loop the array and achieve your desired result like this:
$detail = $this->get_partition($this->input->post(), 17, 2);
$new_array = array();
$count = 0;
foreach($detail as $row){
$new_array[$count]['ID'] = $row[0];
$new_array[$count++]['CODE_DAMAGE'] = $row[1];
}
If the indexes were already correct you could pass the optional third parameter: http://php.net/array_chunk
<?php
$array = array(0 => array(0 => 123, 1 => 1234), 1 => array(0 => 123, 1 => 1234));
$updatedArray = array();
foreach ($array as $k => $v) {
$updatedArray[$k]['ID'] = $v[0];
$updatedArray[$k]['CODE_DAMAGE'] = $v[1];
}
?>
Try this, I hope this helps.
Try this:
foreach($detail as $key => $value){
if($key == 0){
$detail['ID'] = $value;
unset($detail[$key]);
}
if($key == 1){
$detail['CODE_DAMAGE'] = $value;
unset($detail[$key]);
}
}
Just an example add your array to this code..it will work fine
$main = Array(Array(1,9),Array(15,3));
$b = array('ID', 'CODE_DAMAGE');
$new_array = array();
foreach($main as $subarray)
{
$new_array[] = array_combine($b, $subarray);
}
echo'<pre>';print_r($new_array);

how to get array from get to normal array in php

I have an array like this and it can contain multiple values:
Array
(
[rpiid] => Array
(
[1] => 86
)
[sensor_id] => Array
(
[1] => 1
)
[when] => Array
(
[1] => 2014-02-24
)
[val] => Array
(
[1] => 000
)
[train] => Array
(
[1] => True
)
[valid] => Array
(
[1] => False
)
[button] => update
)
Of course, here there is only the number 1 each time but sometimes I have 0, 1, 2 and a value associated. This is because I get this from a GET from multiple forms.
How can I transform this array into
Array
(
[0] => Array
(
[rpiid] => 86
[sensor_id] => 1
...
Thanks,
John.
if your array is $get
$newArray = Array();
foreach($get as $secondKey => $innerArray){
foreach($value as $topKey => $value) {
$newArray[$topKey][$secondKey] = $value;
}
}
This should work
$new_array = array();
foreach($first_array as $value => $key){
$new_array[$key] = $value[1];
}
Sure you can, take a look at this small example:
$a = [ 'rpid' => [1], 'cpid' => [2,2] ];
$nodes = [];
foreach($a as $node => $array) {
foreach($array as $index => $value) {
if(empty($nodes[$index]))
$nodes[$index] = [];
$nodes[$index][$node] = $value;
}
}
print_r($nodes):
Array
(
[0] => Array
(
[rpid] => 1
[cpid] => 2
)
[1] => Array
(
[cpid] => 2
)
)

Combine arrays to form a multidimensional array

I have three arrays:
$arr1 = Array (
[0] => 1001
[1] => 1007
[2] => 1006);
$arr2 = Array (
[0] => frank
[1] => youi
[2] => nashua);
$arr3 = Array (
[0] => getfrankemail
[1] => getyouiemail
[2] => getnashuaemail);
Is there a way to combine these arrays to get a multidimensional array like this:?
Array (
[0] => Array (
[0] => 1001
[1] => frank
[2] => getfrankemail)
[1] => Array (
[0] => 1007
[1] => youi
[2] => getyouiemail)
[2] => Array (
[0] => 1006
[1] => nashua
[2] => getnashuaemail)
);
edit: what you are really looking for is a php version of the zip method in ruby/python.
For your specific example array_map works nicely:
$result = array_map(null, $arr1, $arr2, $arr3);
Output:
array (
0 =>
array (
0 => 1001,
1 => 'frank',
2 => 'frankemail',
),
1 =>
array (
0 => 1007,
1 => 'youi',
2 => 'youiemail',
),
2 =>
array (
0 => 1006,
1 => 'nashua',
2 => 'nashuaemail',
),
)
Iterate on the first array (looks like those are ids), and you can match the key for each value to indexes in $arr2 and $arr3
$result = array();
foreach ($arr1 as $key => $value) {
$result[] = array($value, $arr2[$key], $arr3[$key]);
}
as #kingkero mentions in his answer, you will get errors if they keys do not exist, which you could check for and ignore any rows where that is the case.
$result = array();
foreach ($arr1 as $key => $value) {
if (!isset($arr2[$key]) || !isset($arr3[$key])) {
continue;
}
$result[] = array($value, $arr2[$key], $arr3[$key]);
}
You could use array_push($aContainer, $arr1); or $aContainer[] = $arr[1]
You can do this with a loop in which you access each of the three arrays with the same key.
$result = array();
$max = count($arr1);
for ($i=0; $i<$max; $i++) {
$result[] = array(
$arr1[$i],
$arr2[$i],
$arr3[$i],
);
}
This could fire an out of bounds exception, since it doesn't check whether or not $arrX[$i] exists. Can you be sure that it does?

Remove duplicate elements off a multi-dimension array

I have an array contain this data
Array
(
[id] => Array
(
[0] => 1
[1] => 10
[2] => 4
)
[age] => Array
(
[0] => 1
[1] => 1
[2] => 2
)
)
Now I want to remove duplicates from the ['age'] and leave the first one in tact.
So this would return
Array
(
[id] => Array
(
[0] => 1
[2] => 4
)
[age] => Array
(
[0] => 1
[2] => 2
)
)
Any ideas? Or is there a function already in place to do this?
Like Gordon said, you'd need a custom function to make the relationship but you can use http://php.net/manual/en/function.array-unique.php ?
Wouldn't it be better to have the keys of the age array the corresponding values of the id array?
<?php
$array = array(
'id' => array(0 => 1, 1 => 10, 3 => 4),
'age' => array(0 => 1, 1 => 1, 2 => 2)
);
array_walk($array, 'dupe_killer');
print_r($array);
function dupe_killer(&$value, $key)
{
$value = array_unique($value);
}
?>
You could try this
$array = array('id' => array(1,10,4), 'age'=>array(1,1,2));
$age_array = array();
foreach ($array['age'] as $key => $val) {
if (in_array($val, $age_array))
unset($array['id'][$key], $array['age'][$key]);
$age_array[] = $val;
}
print_r($array);
this returns Array ( [id] => Array ( [0] => 1 [2] => 4 ) [age] => Array ( [0] => 1 [2] => 2 ) )
Regards
Luke

Categories