php merge 2 arrays into one associative array - php

Using PHP I need to merge 2 arrays (of equal length into one associative array) here is an excerpt from my current data set:
[1] => Array
(
[0] => C28
[1] => C29
)
[2] => Array
(
[0] => 1AB010050093
[1] => 1AB008140029
)
both elements [1] and [2] are actually a lot longer than just 2 sub-elements (like I said, this is an excerpt).
The deal is that "C28" in the first array corresponds to "1AB010050093" in the second array, and so on... The result I need is to create a new associative array that looks like this:
[1] => Array
(
['ref'] => C28
['part'] => 1AB010050093
)
[2] => Array
(
['ref'] => C29
['part'] => 1AB008140029
)
and so on...

If you are willing to compromise with an array structure like this:
array(
'C28' => '1AB010050093',
'C29' => '1AB008140029'
);
Then you can use the array_combine() (Codepad Demo):
array_combine($refNumbers, $partIds);
Otherwise, you'll need to use a foreach (Codepad Demo):
$combined = array();
foreach($refNumbers as $index => $refNumber) {
if(!array_key_exists($index, $partIds)) {
throw OutOfBoundsException();
}
$combined[] = array(
'ref' => $refNumber,
'part' => $partIds[$index]
);
}

If you're using PHP 5.5+, there is a new method called array_column(), which will get all of the values in a particular column. That could potentially be used, although I think just a simple foreach loop will probably still be your best bet.

How about:
$arr1 = array(
0 => 'C28',
1 => 'C29',
);
$arr2 = array(
0 => '1AB010050093',
1 => '1AB008140029',
);
$result = array();
for ($i=0; $i<count($arr1); $i++) {
$result[] = array('ref' => $arr1[$i], 'part' => $arr2[$i]);
}
print_r($result);
ouptut:
[1] => Array
(
[0] => C28
[1] => C29
)
[2] => Array
(
[0] => 1AB010050093
[1] => 1AB008140029
)

Related

How to move array in multidimensional array using key value?

How to move array in multidimensional aray with key value?
I'm using array_push to add values to a multidimensional array. i have an array
$myArray = Array(Array('code' => '1','room' => Array('name' => 'Room-A')),Array('code' =>'1','room' => Array('name' => 'Room-B'
)), Array('code' => '2','room' => Array('name' => 'Vip-1')),Array('code' => '2','room' => Array('name' => 'Vip-2')));
i tried using code like this:
for ($i=0; $i <count($myArray) ; $i++) {
if ($myArray[$i]['code']=='1') {
array_push($myArray[$i]['room'], $myArray[$i]['room']);
}
else{
array_push($myArray[$i]['room'], $myArray[$i]['room']);
}
}
i want the result like this :
Array
(
[0] => Array
(
[code] => 1
[room] => Array
(
[0] => Array
(
[name] => Room-A
)
[1] => Array
(
[name] => Room-B
)
)
)
[1] => Array
(
[code] => 2
[room] => Array
(
[0] => Array
(
[name] => Vip-1
)
[1] => Array
(
[name] => Vip-2
)
)
)
)
Any idea how to join this array?
You can use array_reduce to summarize the array into an associative array using the code as the key. Use array_values to convert the associative array into a simple array.
$myArray = ....
$result = array_values(array_reduce($myArray, function($c, $v){
if ( !isset( $c[ $v['code'] ] ) ) $c[ $v['code'] ] = array( 'code' => $v['code'], 'room' => array() );
$c[ $v['code'] ]['room'][] = $v['room'];
return $c;
},array()));
echo "<pre>";
print_r( $result );
echo "</pre>";
This will result to:
Array
(
[0] => Array
(
[code] => 1
[room] => Array
(
[0] => Array
(
[name] => Room-A
)
[1] => Array
(
[name] => Room-B
)
)
)
[1] => Array
(
[code] => 2
[room] => Array
(
[0] => Array
(
[name] => Vip-1
)
[1] => Array
(
[name] => Vip-2
)
)
)
)
This is the foreach() equivalent of Eddie's answer (I find it easier to read/maintain).
Code: (Demo)
$myArray = [
['code' => '1', 'room' => ['name' => 'Room-A']],
['code' => '1', 'room' => ['name' => 'Room-B']],
['code' => '2', 'room' => ['name' => 'Vip-1']],
['code' => '2', 'room' => ['name' => 'Vip-2']]
];
foreach ($myArray as $row) {
if (!isset($result[$row['code']])) {
$result[$row['code']] = ['code' => $row['code'], 'room' => [$row['room']]];
// ^------------^-- pushed deeper
} else {
$result[$row['code']]['room'][] = $row['room'];
// ^^-- pushed deeper
}
}
var_export(array_values($result));
This question is very similar to many pre-existing questions that want to group by a particular column. I was not able to find an exact duplicate to close with because the requirement of this question is to created a deeper structure to contain the room sub arrays.
Typically I would write:
if (!isset($result[$row['code']])) {
$result[$row['code']] = $row;
to cut down on syntax, but the new output structure must be applied to both the if and the else.
To avoid key duplication/collision, the room subarrays need to be pushed/indexed to a lower level.
In the end, the technique has been demonstrated here many, many times on StackOverflow. You target an element value to group by and use that value as the temporary key as you iterate the input array. Checking if the temporary keys exist or not is the fastest way to determine if a group is new or previously encountered. When you are done, call array_values() to remove the temporary keys (re-index the array).

Multidimensional associative array: how to find array with same value?

I'm currently looking for a solution to this problem:
if I have something like that:
Array
(
[0] => Array
(
[id] => 1
[name] => Timer
)
[1] => Array
(
[id] => 2
[name] => Tub
)
[3] => Array
(
[id] => 1
[name] => Paper
)
[4] => Array
(
[id] => 4
[name] => Puppy
)
)
The goal I'd like to reach here is create a new array which contains the arrays with the same ID. So basically, at the end I'm gonna have two arrays: the first will contain element with different IDs and the second will contain element with the same ID.
Any tips? Thank you in advance!
One way is by mainly using array_filter()
// Gather ids and count
$id = array_count_values(array_column($array, 'id'));
// Filter not unique
$notUnique = array_filter($array, function($e) use ($id) {
return ($id[$e['id']] > 1);
});
// Filter unique
$unique = array_filter($array, function($e) use ($id) {
return !($id[$e['id']] > 1); // or ($id[$e['id']] == 1)
});
// Print result
print_r($notUnique);
echo '<br>';
print_r($unique);
Try this
<?php
$array = array(
array('id' => 1,'name' => 'Timer'),
array('id' => 2,'name' => 'Tub'),
array('id' => 1,'name' => 'Paper'),
array('id' => 4,'name' => 'Puppy')
);
$new = array();
foreach($array as $r)$new[$r['id']][] = $r['name'];
echo '<pre>';print_r($new);
?>
Output
Array
(
[1] => Array
(
[0] => Timer
[1] => Paper
)
[2] => Array
(
[0] => Tub
)
[4] => Array
(
[0] => Puppy
)
)

build dynamic associative multi-dimensional array

I have seen a lot of questions regarding multi-dimensional arrays, and how to build them, and whilst trying some of the answers I still get an error. So I am thinking what I am trying to do is not really possible, and perhaps I should use JSON instead?
I have data from a source which is returned as a JSON object. It has lots data in it, of which i only need a small amount. Now I need it sorted into dates:
$temp_array = array();
foreach ($data as $booking_id => $booking) {
$setdate = '';
$b = $this->getBooking($booking_id);
foreach ($b as $k => $v) {
$setdate = date('d-m-Y', $booking['start_date']);
if(!in_array($setdate, $temp_array)) {
$temp_array = array('date' => $setdate);
}
$temp_array['date'][] = array($k => $v);
}
}
I need the date to be the first node of the array, and the data to be in the second node. When a new date is found in the iteration, it creates another new node:
[0] => 1/10/16
[0] => array( ['key'] =>['value'])
[1] => array( ['key'] =>['value'])
[2] => array( ['key'] =>['value'])
[1] => 7/10/16
[0] => array( ['key'] =>['value'])
[1] => array( ['key'] =>['value'])
[2] => array( ['key'] =>['value'])
[2] => 14/10/16
[0] => array( ['key'] =>['value'])
[1] => array( ['key'] =>['value'])
[2] => array( ['key'] =>['value'])
[3] => 21/10/16
[0] => array( ['key'] =>['value'])
[1] => array( ['key'] =>['value'])
[2] => array( ['key'] =>['value'])
I seem unable to get anywhere with it as the errors I get refer to [] operator not supported for strings or Warning: Attempt to modify property of non-object in depending on what other examples on here I have found.
I think the question here, is that the data is not in any order, so it may populate node [0], and then [3], and then back to [0], and so on.
Any ideas what on earth I am doing wrong ?
Thanks
Addy
Update
Using this code, which is the middle foreach:
$b = $this->getBooking($booking_id);
foreach ($b as $k => $v) {
$setdate = date('d-m-Y', strtotime($booking['date_desc']));
if(!in_array($setdate, $temp_dates)) {
array_push($temp_dates, $setdate);
$temp_array[]['date'] = $setdate;
}
}
Gives me this result:
Array ( [0] => Array ( [date] => 22-10-2016 )
[1] => Array ( [date] => 01-10-2016 )
[2] => Array ( [date] => 08-10-2016 )
[3] => Array ( [date] => 15-10-2016 )
)
Which is correct. So now, I need to add, each time a date arrives which $tem_array has a heading for, add another array:
Array ( [0] => Array ( [date] => 22-10-2016 ) => [0] => $data
[1] => $data
[2] => $data
[1] => Array ( [date] => 01-10-2016 ) => [0] => $data
[1] => $data
[2] => $data
[2] => Array ( [date] => 08-10-2016 ) => [0] => $data
[3] => Array ( [date] => 15-10-2016 ) => [0] => $data
[1] => $data
)
Hope this explains it a little better. I have the first bit correct, but when a date is already in there, I need to move up a node.
I think I was over complicating it. This is the final code which did want I wanted.
function sortcf($data) {
$temp_array = array();
$temp_dates = array();
foreach ($data as $booking_id => $booking) {
$b = $this->getBooking($booking_id);
$setdate = date('d-m-Y', strtotime($booking['date_desc']));
$temp_array[$setdate][] = ($b);
}
$this->wcg_am_data = $temp_array;
}

Once more about removing duplicate values from a multi-dimensional array in PHP

After an exhausting search I found some similar problems like the one I would like to solve, but I could not use their answers.
Hier are some very good examples:
How to remove duplicate values from a multi-dimensional array in PHP
How to remove duplicate values from a multi-dimensional array in PHP
How to remove duplicate values from a multi-dimensional array in PHP revisited
This one is the most similar, but the answer somehow doesn't work to me.
php filter array values and remove duplicates from multi dimensional array
The main difference to my issue is that while people are looking for a solution to delete an entire duplicated subarray from the array, I'm trying to delete the subarray when only one $key => $value pair of the subarray is similar to the correspondent pair of another subarray. The other pairs could have different values or even the same.
Here my array:
Array(
[0] => Array
(
[0] => AAA
[1] => 500
)
[1] => Array //Won't be delete 'cause [0] is different, although [1] is the same.
(
[0] => BBB
[1] => 500
)
[2] => Array //Will be delete 'cause [0] is the same.
(
[0] => AAA
[1] => 500
)
[3] => Array //Won't be delete 'cause [0] is different.
(
[0] => CCC
[1] => 820
)
[4] => Array
(
[0] => AAA //Will be delete 'cause [0] is the same. [1] is also different.
[1] => 774
)
How could I manage to delete these subarrays so I have following result:
Array(
[0] => Array
(
[0] => AAA
[1] => 500
)
[1] => Array
(
[0] => BBB
[1] => 500
)
[2] => Array
(
[0] => CCC
[1] => 820
)
Many thanks in advance!
The easiest solution (in my opinion), instead of using magical array_filter and array_map handicraft which is difficult to maintain, is to write a specialized function yourself:
$out = [];
$usedKeys = [];
foreach ($in as $element)
{
list ($a, $b) = $element;
if (!isset($usedKeys[$a]))
{
$usedKeys[$a] = true;
$out[]= $element;
}
}
var_dump($out);
This will return only elements whose first pair element is unique (taking first one, if multiple entries are available).
This works for me (based on the link provided):
<?php
$items = array(
array(
0 => 'AAA',
1 => 500,
),
array(
0 => 'BBB',
1 => 500,
),
array(
0 => 'AAA',
1 => 500,
),
array(
0 => 'CCC',
1 => 820,
),
array(
0 => 'AAA',
1 => 774,
),
);
$taken = array();
foreach($items as $key => $item) {
if(!in_array($item[0], $taken)) {
$taken[] = $item[0];
} else {
unset($items[$key]);
}
}
echo '<pre>'.print_r($items,true).'</pre>';
fiddle link

Assigning Index to PHP Array

I dynamically pull the following array from mysql table and need to assign index to each of the element.
Array
(
[yma] => 65.0000
[mhip] => 65.0000
[tzp] => 40.0000
[mzp] => 45.0000
[su] => 40.0000
[tkp] => 74.0000
)
here is my expected output.
Array
(
[0][yma] => 65.0000
[1][mhip] => 65.0000
[2][tzp] => 40.0000
[3][mzp] => 45.0000
[4][su] => 40.0000
[5][tkp] => 74.0000
)
Or
Array
(
[0] => 65.0000
[1] => 65.0000
[2] => 40.0000
[3] => 45.0000
[4] => 40.0000
[5] => 74.0000
)
There can be issue with the answer below if my desired output is like below:
Array
(
[0] => 'yma'
[1] => 'mhip'
[2] => 'tzp'
[3] => 'mzp'
[4] => 'su'
[5] => 'tkp'
)
I am using this code for pulling the data:
$myarray = array();
while($row = mysql_fetch_array($sql)){
$myarray[$row['pawl']] = $row['contribution'];
}
How can I take the array I am fetching/building from MySQL and generate the desired output?
Use array_values. "Array_values() returns all the values from the array and indexes the array numerically."
Also,
$myarray = array();
while($row = mysql_fetch_array($sql)){
$myarray[] = $row['contribution'];
}
This will assign a numeric index starting from 0.
Now, if you need a specific numeric index to match each pawl code,
Then build a map:
$map = array
(
['yma'] => 1,
['mhip'] => 2,
['tzp'] => 3,
['mzp'] => 4,
['su'] => 5,
['tkp'] => 6,
);
And Remap the pawl codes.
$remappedArray = array();
foreach($myarray as $pawlCode => $value){
$newIndex = $map[$pawlCode];
$remappedArray[$newIndex] = $value;
}
How you want to handle missing/new codes is up to you.
In order to create the array you want (I will focus on example two because it is more reasonable) you just need one function - array_values.
Given an input array of
Array
(
[yma] => 65.0000
[mhip] => 65.0000
[tzp] => 40.0000
[mzp] => 45.0000
[su] => 40.0000
[tkp] => 74.0000
)
It will return a numerically indexed array of just the values, which will look like this:
Array
(
[0] => 65.0000
[1] => 65.0000
[2] => 40.0000
[3] => 45.0000
[4] => 40.0000
[5] => 74.0000
)
If you need the keys, rather than the values you can simply use the array_keys function on the same starting array (see input array above) - and you will get the following output:
Array
(
[0] => 'yma'
[1] => 'mhip'
[2] => 'tzp'
[3] => 'mzp'
[4] => 'su'
[5] => 'tkp'
)
PHP has a large suite of array functions and in general you can most likely find a function to help you get/do whatever you need with an array. I encourage you to take some time and scan through these at some point. It pays to know what is available to you.
Use this for your first expected array:
$myarray = array();
while($row = mysql_fetch_array($sql)){
$myarray[] = array($row['pawl'] => $row['contribution']);
}
And this for your second expected array:
$myarray = array();
while($row = mysql_fetch_array($sql)){
$myarray[] = $row['contribution'];
}

Categories