How do i get the final array? - php

I have a array here:
$array = array(
array('t'=>'t1','v'=>'001'),
array('t'=>'t2','v'=>'002'),
array('t'=>'t3','v'=>'003'),
array('t'=>'t1','v'=>'004'),
array('t'=>'t4','v'=>'005'),
array('t'=>'t2','v'=>'006'),
array('t'=>'t5','v'=>'007'),
array('t'=>'t3','v'=>'008'),
);
The final array i want is this :
array(
't1' => array('v'=>array(001,004)),
't2' => array('v'=>002),
't3' => array('v'=>array(003,008)),
't4' => array('v'=>005),
't5' => array('v'=>006),
't6' => array('v'=>007)
)
Is there any way i can achieve the final array using php array manipulation functions? I don't want to use any loops (for or foreach). Tried doing using usort() but getting no where
Here is my usort code that calls user defined function:
public function sort($a,$b)
{
$const = array();
$temp1 = array();
$temp2 = array();
//echo $a['t'].":".$a['v'] . " - " . $b['t'].":".$b['v']. "<br/>";
if($a['t'] == $b['t']){
$temp1[$a['t']] = array($a['v'],$b['v']);
//$const = $temp1;
}else{
if(!array_key_exists($a['t'],$temp1) && !array_key_exists($b['t'],$temp1)){
$temp2[$a['t']] = array($a['v']);
$temp2[$b['t']] = array($b['v']);
}
}
$result = array_merge($temp1, $temp2);
print_r($result);
}

$array = array(
array('t'=>'t1','v'=>'001'),
array('t'=>'t2','v'=>'002'),
array('t'=>'t3','v'=>'003'),
array('t'=>'t1','v'=>'004'),
array('t'=>'t4','v'=>'005'),
array('t'=>'t2','v'=>'006'),
array('t'=>'t5','v'=>'007'),
array('t'=>'t3','v'=>'008'),
);
$res = array();
foreach($array as $val){
$res[$val['t']]['v'][] = $val['v'];
}
echo "<pre>";
print_r($res);
Output :
Array
(
[t1] => Array
(
[v] => Array
(
[0] => 001
[1] => 004
)
)
[t2] => Array
(
[v] => Array
(
[0] => 002
[1] => 006
)
)
[t3] => Array
(
[v] => Array
(
[0] => 003
[1] => 008
)
)
[t4] => Array
(
[v] => Array
(
[0] => 005
)
)
[t5] => Array
(
[v] => Array
(
[0] => 007
)
)
)

<?php
$array = array(
array('t'=>'t1','v'=>'001'),
array('t'=>'t2','v'=>'002'),
array('t'=>'t3','v'=>'003'),
array('t'=>'t1','v'=>'004'),
array('t'=>'t4','v'=>'005'),
array('t'=>'t2','v'=>'006'),
array('t'=>'t5','v'=>'007'),
array('t'=>'t3','v'=>'008'),
);
foreach ($array as $key => $row) {
$t[$key] = $row['t'];
$v[$key] = $row['v'];
}
array_multisort($v, SORT_ASC, $array);
$reqArray = array();
foreach($array as $value)
{
$reqArray[$value['t']]['v'][] = $value['v'];
}
print_r($reqArray);
?>

Try with:
$input = array( /* your data */ );
$output = array();
foreach ( $input as $value ) {
$t = $value['t'];
$v = $value['v'];
if ( !isset($output[$t]) ) {
$output[$t] = array('v' => $v);
} else if ( is_array($output[$t]['v']) ) {
$output[$t]['v'][] = $v;
} else {
$output[$t]['v'] = array($output[$t]['v'], $v);
}
}

Related

Merging 3 arrays in PHP

I have 3 arrays as below.
$array1 = Array
(
[0] => 05/01
[1] => 05/02
)
$array2 =Array
(
[0] => ED
[1] => P
)
$array3 =Array
(
[0] => Mon
[1] => Tue
)
I want to merge these 3 arrays as below $result_array. I have written a code as below. But It gave a empty array.
$result_array =Array
(
[0] => Array
(
[0] => 05/01
[1] => ED
[2] => Mon
)
[1] => Array
(
[0] => 05/02
[1] => P
[2] => Tue
)
)
Code:
for($z=0; $z<count($array1); $z++){
$all_array[$z][] = array_merge($array1[$z],$array2[$z] );
$all_array2[$z] = array_merge($all_array[$z],$array3[$z] );
}
Please help me to do this.
Simply foreach over the first array and use the index as the key to the other arrays.
foreach ( $array1 as $idx => $val ) {
$all_array[] = [ $val, $array2[$idx], $array3[$idx] ];
}
Remember this will only work if all 3 arrays are the same length, you might like to check that first
You can simply walk through the first array with a foreach loop then access the corresponding arrays and combine the results into one big array. This will only work if the arrays are the same length so it's worth checking that before to stop any errors. Something like this:
<?php
$arr1 = ['05/01', '05/02'];
$arr2 = ['ED', 'P'];
$arr3 = ['Mon', 'Tue'];
$combined = [];
if (count($arr1) != count($arr2) || count($arr1) != count($arr3))
die("Array lengths do not match!");
foreach ($arr1 as $key => $val) {
$combined[] = [$val, $arr2[$key], $arr3[$key]];
}
var_dump($combined);
You can see an eval.in of this working here - https://eval.in/833893
Create an sample array and push to each array value with respective key
$sample = array();
for($z=0; $z<count($array1); $z++){
$sample[]=array($array1[$z],$array2[$z],$array3[$z]);
}
print_r($sample);
Out put is
Array ( [0] => Array (
[0] => 05/01
[1] => ED
[2] => Mon
)
[1] => Array (
[0] => 05/02
[1] => P
[2] => Tue
)
)
this work for n of arrays and dynamic length of array
function mergeArrays(...$arrays)
{
$length = count($arrays[0]);
$result = [];
for ($i=0;$i<$length;$i++)
{
$temp = [];
foreach ($arrays as $array)
$temp[] = $array[$i];
$result[] = $temp;
}
return $result;
}
$x = mergeArrays(['05/01' , '05/02'] , ['ED' , 'P'] , ['Mon' , 'Tus']);
$y = mergeArrays(['05/01' , '05/02' , 'X'] , ['ED' , 'P' , 'Y'] , ['Mon' , 'Tus' , 'Z'] , ['A' , 'B' , 'C']);
var_dump($x);
var_dump($y);
function merge($file_name, $titles, $description)
{
$result = array();
foreach($file_name as $key=>$name )
{
$result[] = array( 'file_name' => $name, 'title' => $titles[$key],
'description' => $description[ $key ] );
}
return $result;
}
$array1 = Array
(
'05/01',
'05/02'
);
$array2 = Array
(
'ED',
'P'
);
$array3 =Array
(
'Mon',
'Tue'
);
$result_array = array();
foreach ($array1 as $key=>$val)
{
$result_array[$key] = array($array1[$key],$array2[$key],$array3[$key]);
}
echo "<PRE>"; print_r($result_array);

Adding same element to every level of array php

I need to add another another element to each level of the array (sorry, think that is bad terminology).
I have an array -
Array ( [0] => Array (
[actor_rt_id] => 162683283,
[item_number] => 3 )
[1] => Array (
[actor_rt_id] => 162657351,
[item_number] => 5 )
)
This code produces the array. The commented out line is what I tried to add to the array. The code before the comment creates the array.
$data_itemone['actor_rt_id'] = $this->input->post('actor_id');
$data_itemtwo['item_number'] = $this->input->post('item_number');
$data_item = array_merge($data_itemone, $data_itemtwo);
$res = [];
foreach($data_item as $key => $value){
foreach ($value as $data => $thevalue) {
$res[$data][$key] = $thevalue;
//$res['film_id'] = $film_id;
}
}
I have an another variable I need to add from post which is a single string.
$film_id = $this->input->post('film_id');
I need it to be in the array like so -
Array ( [0] => Array (
[actor_rt_id] => 162683283,
[item_number] => 3,
[film_id] => 52352
)
[1] => Array (
[actor_rt_id] => 162657351,
[item_number] => 5,
[film_id] => 52352
)
)
...but my code (uncommented) produces -
Array ( [0] => Array (
[actor_rt_id] => 162683283,
[item_number] => 3
)
[film_id] => 16639,
[1] => Array
( [actor_rt_id] => 162657351,
[item_number] => 5 )
)
Tried a few things. Can't seem to get it to work.
Change
$res['film_id'] = $film_id;
to
$res[$data]['film_id'] = $film_id;
this will add it to the right array.
How if you try this.
$data_itemone['actor_rt_id'] = [123, 245];
$data_itemtwo['item_number'] = [456, 789];
$film_id = 52352;
$data_item = array_merge($data_itemone, $data_itemtwo);
$res = [];
foreach($data_item as $key => $value){
foreach ($value as $data => $thevalue) {
$res[$data][$key] = $thevalue;
$res[$data]['film_id'] = $film_id;
}
}
print_r($res);
Try this one
<?
$data_itemone['actor_rt_id'] = $this->input->post('actor_id');
$data_itemtwo['item_number'] = $this->input->post('item_number');
$film_id = $this->input->post('film_id');
$data_item = array_merge($data_itemone, $data_itemtwo);
$res = [];
foreach($data_item as $key => $value){
foreach ($value as $data => $thevalue) {
$res[$data][$key] = $thevalue;
$res[$data]['film_id'] = $film_id;
}
}
?>

Parse a php array that has float index into new array

I have an array with float indexes that I'm getting from a plugin. I want to parse this array and take the ones that are float and put them in as a new array. Meaning what I have is
[1] => gsurvey128f54af2
[2] => gsurvey282bd4253
[5.1] => gsurvey5649a964f
[5.2] => gsurvey5fddb5e9f
[5.3] => gsurvey533c5b311
[5.4] => gsurvey5c8933efb
[5.5] => gsurvey5da48f59b
What I want is:
[1] => gsurvey128f54af2
[2] => gsurvey282bd4253
[5] => array (
[0] => gsurvey5649a964f
[1] => gsurvey5fddb5e9f
[2] => gsurvey533c5b311
[3] => gsurvey5c8933efb
[4] => gsurvey5da48f59b
)
I'm not clear on what's the best way to approach this.
I made the comment above that this problem is very prone to error because it is possible to have input that would set a single value to be both a string and an array at the same time. That will obviously fail. Assuming that the input is clean...
$new_array = array();
foreach($old_array as $key=>$val)
{
$a = explode('.', $key);
if(sizeof($a)==2)
{
if(!isset($new_array[$a[0]])) $new_array[$a[0]] = array();
$new_array[$a[0]][] = $val;
}
else $new_array[$key]=$val;
}
Example with array_walk:
$array = array (
'1' => 'gsurvey128f54af2',
'2' => 'gsurvey282bd4253',
'5.1' => 'gsurvey5649a964f',
'5.2' => 'gsurvey5fddb5e9f',
'5.3' => 'gsurvey533c5b311',
'5.4' => 'gsurvey5c8933efb',
'5.5' => 'gsurvey5da48f59b'
);
$output = array();
array_walk( $array, function( $item, $key ) use ( &$output ) {
$keys = explode( '.', $key );
isset( $keys[1] ) ? $output[ $keys[0] ][ $keys[1] ] = $item : $output[ $keys[0] ] = $item;
});
print_r( $output );
/*
Array
(
[1] => gsurvey128f54af2
[2] => gsurvey282bd4253
[5] => Array
(
[1] => gsurvey5649a964f
[2] => gsurvey5fddb5e9f
[3] => gsurvey533c5b311
[4] => gsurvey5c8933efb
[5] => gsurvey5da48f59b
)
)
*/
For this specific case, this should work:
foreach($array as $k => $v) {
if(count($i = explode('.', $k)) > 1) {
$result[$i[0]][] = $v;
} else {
$result[$k] = $v;
}
}

How to merge two array in according to value in PHP?

I have two array and I need to merge it together !!
Array 1
Array
(
[0] => Array
(
[brand] => CARTIER
[amount_2014] => 136476
)
[1] => Array
(
[brand] => TIFFANY & CO.
[amount_2014] => 22000
)
[2] => Array
(
[brand] => Test
[amount_2014] => 33000
)
)
Array 2
Array
(
[0] => Array
(
[brand] => CARTIER
[amount_2013] => 22052
)
[1] => Array
(
[brand] => Test
[amount_2013] => 3313
)
)
I need the result array as:
Array
(
[0] => Array
(
[brand] => CARTIER
[amount_2014] => 136476
[amount_2013] => 22052
)
[1] => Array
(
[brand] => TIFFANY & CO.
[amount_2014] => 22000
[amount_2013] => 0
)
[2] => Array
(
[brand] => Test
[amount_2014] => 33000
[amount_2013] => 3313
)
)
So for every [brand] I need the amount in [amount_2014] & [amount_2013], if any one is not present then I need it value as 0;
I am using CodeIgniter for this project, I have only one table with field (brand, amount, year) am issuing two queries for getting sum of amount for 2013 & 2014.
(I am fighting with array_merge and array_combine but no use for me in this case, if any one can help with query then it's also very much helpful).
Try this:
function cars_array_merge()
{
$arrays = func_get_args();
foreach ($arrays as &$array)
{
$new_arr = array();
foreach ($array as $value)
{
$brand = $value['brand'];
unset($value['brand']);
$new_arr[$brand] = $value;
}
$array = $new_arr;
}
$arrays = call_user_func_array('array_merge_recursive', $arrays);
foreach ($arrays as $brand => &$array)
$array['brand'] = $brand;
return array_values($arrays);
}
// testing
$arr1 = [
[ 'brand' => 'CARTIER', 'mount_2014' => 136476 ],
[ 'brand' => 'TIFFANY & CO.', 'mount_2014' => 22000 ]
];
$arr2 = [
[ 'brand' => 'CARTIER', 'mount_2013' => 22052 ]
];
print_r(cars_array_merge($arr1, $arr2));
Output:
Array
(
[0] => Array
(
[mount_2014] => 136476
[mount_2013] => 22052
[brand] => CARTIER
)
[1] => Array
(
[mount_2014] => 22000
[brand] => TIFFANY & CO.
)
)
<?php
for ($i = 0, $max = count($arr1); $i < $max; ++$i) {
$arr1[$i]['amount_2013'] = isset($arr2[$i]['amount_2013']) ? $arr2[$i]['amount_2013'] : 0;
}
$merge = array_merge($arr1, $arr2);
$temp = $merge;
$newArr = array(); $key_array = array();
foreach($merge as $key=>$val){
$b = $val['brand'];
$a1 = isset($val['amount_2013']) ? $val['amount_2013'] : 0;
$a2 = isset($val['amount_2014']) ? $val['amount_2014'] : 0;
unset($temp[$key]);
foreach($temp as $k=>$values){
if($values['brand'] == $b){
if($a1 == 0){
$a1 = isset($values['amount_2013']) ? $values['amount_2013'] : 0;
}
if($a2 == 0){
$a2 = isset($values['amount_2014']) ? $values['amount_2014'] : 0;
}
unset($temp[$k]);
}
}
if(!in_array($b, $key_array))
{
$newArr[] = array('brand' => $b, 'amount_2014' => $a2, 'amount_2013' => $a1);
}
$key_array[] = $b;
}
print_r($newArr);
This is what I used:
<?php
$arr1 = array(0=>array("brand"=>"CARTIER","amount_2014"=>136476), 1=>array("brand"=>"tiffany","amount_2014"=>22000));
$arr2 = array(0=>array("brand"=>"CARTIER","amount_2013"=>22000));
foreach ($arr2 as $key=>$value){
if( $value["brand"] == "CARTIER")
{
$arr1[0]["amount_2013"] = $value["amount_2013"];
$arr1[1]["amount_2013"] = 0;
}
else
{
$arr1[1]["amount_2013"] = $value["amount_2013"];
$arr1[0]["amount_2013"] = 0;
}
}
print_r($arr1);
?>

Splitting keys from values into another array

I have a function to convert a .json file to an array:
function jsonToArray($file) {
$json = json_decode(file_get_contents($file), true);
print_r($json); }
This yields an array like this:
Array (
[field1] => value1
[field2] => Array
(
[subfield1] => subvalue1
[subfield2] => subvalue2
[subfield3] => subvalue3
)
)
To interface with existing code, I need these arrays with the fields and values split, like this:
Array (
[0] => Array
(
[0] => field1
[1] => Array
(
[0] => subfield1
[1] => subfield2
[2] => subfield3
)
)
[1] => Array
(
[0] => value1
[1] => Array
(
[0] => subvalue1
[1] => subvalue2
[2] => subvalue3
)
)
)
The code I came up with works if this structure is maintained for all usage but as that can't be guaranteed I need another solution. I'm sure it's something relatively simple, I just can't crack it. Any hints or insight would be much appreciated.
try this code
$arr = array ('field1' => 'value1',
'field2' => array(
'subfield1' => 'subvalue1',
'subfield2' => 'subvalue2',
'subfield3' => 'subvalue3'));
function array_values_recursive($ary) {
$lst = array();
foreach( $ary as $k => $v ) {
if (is_scalar($v)) {
$lst[] = $v;
} elseif (is_array($v)) {
$lst[] = array_values_recursive($v);
}
}
return array_values($lst);
}
function array_keys_recursive($ary) {
$lst = array();
foreach( $ary as $k => $v ) {
if (is_scalar($v)) {
$lst[] = ($k);
} elseif (is_array($v)) {
$lst[] = array_keys_recursive($v);
}
}
return $lst;
}
echo '<pre>';
$arr1 = array();
$arr1[] = array_values_recursive($arr);
$arr1[] = array_keys_recursive($arr);
print_r($arr1);
This might be useful to you: array_values() and array_keys() that and a little of foreach would do the magic.

Categories