PHP merge arrays in specific order, not simply append them - php

I have two arrays:
Array ( [0] => a [1] => b [2] => c [3] => d )
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
I want to merge them so they end up like this:
Array ( [0] => a [1] => 1 [2] => b [3] => 2 [4] => c [5] => 3 [6] => d [7] => 4 )
Something like array 1[1], array 2[1], array 1[2], array 2[2], etc.
It's probably simple but I can't find an answer anywhere!

You would have to use a loop as far as I know, based on the length of the longest array.
// input arrays
$array1 = array( 1, 2, 3, 4 );
$array2 = array( 'a', 'b', 'c', 'd' );
// output arrays
$array3 = array();
// get the longest for the loop
$length = count($array1) > count($array2)? count($array1) : count($array2);
// if there is an element set for the index append to the output array
for ( $i=0; $i<$length; $i++ ){
if ( isset($array1[$i]) ) $array3[] = $array1[$i];
if ( isset($array2[$i]) ) $array3[] = $array2[$i];
}
print_r( $array3 );
Results in:
Array ( [0] => 1 [1] => a [2] => 2 [3] => b [4] => 3 [5] => c [6] => 4 [7] => d )
Run in this PHP Fiddle.

Related

Count consecutive repeated elements in array in the same sequence as they are

I need to count consecutive repeated elements in the array, but if they are non consecutive I want to count them also, to have them in the same sequence as they are.
For example I have flowing array:
$array = Array('a', 'b', 'a', 'a', 'a', 'c', 'c', 'b', 'b', 'a', 'a', 'a', 'a');
if I use array_count_values function
example:
print_r(array_count_values($array));
Output will be:
Array ( [a] => 8 [b] => 3 [c] => 2 )
But I need to get output like this:
element counted value
a 1
b 1
a 3
c 2
b 2
a 4
You can iterate over the array, counting values while they are the same, and pushing a value to the result array when they are different:
$result = [];
$count = 0;
$current = $array[0];
for ($i = 0; $i < count($array); $i++) {
if ($array[$i] == $current) {
$count++;
}
else {
$result[] = array($current, $count);
$count = 1;
}
$current = $array[$i];
}
$result[] = array($current, $count);
print_r($result);
Output:
Array
(
[0] => Array
(
[0] => a
[1] => 1
)
[1] => Array
(
[0] => b
[1] => 1
)
[2] => Array
(
[0] => a
[1] => 3
)
[3] => Array
(
[0] => c
[1] => 2
)
[4] => Array
(
[0] => b
[1] => 2
)
[5] => Array
(
[0] => a
[1] => 4
)
)
Demo on 3v4l.org
Starting with an array with the first item from the source (and a count of 1), this then starts from the second item and checks if it matches the one in the current output. Adding 1 if it matches or adding a new entry if it doesn't...
$array = Array ('a','b','a','a','a','c','c','b','b','a','a','a','a');
$output = [ ["element" => $array[0], "count" => 1 ] ];
$outputPoint = 0;
for ( $i = 1, $count = count($array); $i < $count; $i++ ) {
if ( $array[$i] == $output[$outputPoint]["element"] ) {
$output[$outputPoint]["count"]++;
}
else {
$output[++$outputPoint] = ["element" => $array[$i], "count" => 1 ];
}
}
print_r($output);
Which outputs...
Array
(
[0] => Array
(
[element] => a
[count] => 1
)
[1] => Array
(
[element] => b
[count] => 1
)
[2] => Array
(
[element] => a
[count] => 3
)
[3] => Array
(
[element] => c
[count] => 2
)
[4] => Array
(
[element] => b
[count] => 2
)
[5] => Array
(
[element] => a
[count] => 4
)
)
This loops through the array and increments the number of elements in $count.
$array = ['a','b','a','a','a','c','c','b','b','a','a','a','a'];
$count = [];
$crt = -1;
foreach($array ?? [] as $element) {
if($crt == -1 || $count[$crt]["element"] != $element) {
$count[++$crt] = ["element" => $element, "counted_value" => 1];
} else {
$count[$crt]["counted_value"]++;
}
}
The array looks like:
Array
(
[0] => Array
(
[element] => a
[counted_value] => 1
)
[1] => Array
(
[element] => b
[counted_value] => 1
)
[2] => Array
(
[element] => a
[counted_value] => 3
)
[3] => Array
(
[element] => c
[counted_value] => 2
)
[4] => Array
(
[element] => b
[counted_value] => 2
)
[5] => Array
(
[element] => a
[counted_value] => 4
)
)
Compare 2 elements by iterating the array, if both the elements are the same, increase the count else keep the count as 1
$index = 0;
$finalArr[$index] = array('ele'=>$array[0],'cnt'=>1);
for($i=1; $i<count($array); $i++)
{
if($array[$i]===$array[$i-1])
{
++$finalArr[$index]['cnt'];
}
else
{
$finalArr[++$index] = array('ele'=>$array[$i],'cnt'=>1);
}
}
print_r($finalArr);

Transform 2d array in php?

i need a function that transforms a 2d array from:
1 4
2 5
3 6
to
1 2
3 4
5 6
my first approach was by transforming the matrix with
array_unshift($data, null);
call_user_func_array('array_map', $data);
But now i got:
1 5
2 6
3
4
Can someone help?
Edit:
Ok let me be more clear i have these categories and i need to reorder them in this way
Array
(
[0] => Array
(
[0] => Das ist los
[1] => Land & Leute
[2] => Wirtschaft & Politik
[3] => Leben
[4] => Kultur
)
[1] => Array
(
[0] => Chronik
[1] => Motor
[2] => Sport
[3] => Blaulicht
[4] => Schauplatz
)
)
I need:
Array
(
[0] => Array
(
[0] => Das ist los
[1] => Wirtschaft & Politik
[2] => Kultur
[3] => Motor
[4] => Blaulicht
)
[1] => Array
(
[0] => Land & Leute
[1] => Leben
[2] => Chronik
[3] => Sport
[4] => Schauplatz
)
)
For a simple 2-column array:
$myArray = [
[1,4],
[2,5],
[3,6],
];
$myNewArray = array_chunk(
array_merge(
array_column($myArray, 0),
array_column($myArray, 1)
),
2
);
var_dump($myNewArray);
EDIT
For a more generic solution:
$myArray = [
[1,6,11],
[2,7,12],
[3,8,13],
[4,9,14],
[5,10,15],
];
$columns = count($myArray[0]);
$tmpArray = [];
for($i = 0; $i < $columns; ++$i) {
$tmpArray = array_merge(
$tmpArray,
array_column($myArray, $i)
);
}
$myNewArray = array_chunk(
$tmpArray,
$columns
);
var_dump($myNewArray);

PHP merge single array elements into unique array

I'm not sure how to work the title of this question, so sorry if it's a little confusing.
I have an array;
Array
(
[username] => Array
(
[0] => 'a'
[1] => 'b'
[2] => 'c'
[3] => 'd'
[4] => 'e'
[5] => 'f'
)
[email] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
[5] =>
)
[level] => Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
[4] => 1
[5] => 1
)
[role] => Array
(
[0] => 2
[1] => 1
[2] => 1
[3] => 1
[4] => 2
[5] => 1
)
[password] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
[5] =>
)
[id] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
)
But I want it in this format:
Array
(
[0] => Array
(
[username] => 'a'
[id] => 'a'
[email] => 'a'
)
[1] => Array
(
[username] => 'a'
[id] => 'a'
[email] => 'a'
)
[2] => Array
(
[username] => 'a'
[id] => 'a'
[email] => 'a'
)
[3] => Array
(
[username] => 'a'
[id] => 'a'
[email] => 'a'
)
[4] => Array
(
[username] => 'a'
[id] => 'a'
[email] => 'a'
)
[5] => Array
(
[username] => 'a'
[id] => 'a'
[email] => 'a'
)
I can't seem to figure it out, arrays end too soon, or there ends up being too many indexes etc. Ideas?
I would loop through the array and reconstruct it like so:
$index_count = count($array['username']); // in your case, this is 6
$new_array = array();
for ($i = 0; $i < $index_count; $i++) {
$new_array[] = array(
'username' => $array['username'][$i],
'email' => $array['email'][$i],
'id' => $array['id'][$i]
);
}
UPDATE If you want this to take into consideration any and all possible keys, try this:
$keys = array_keys($array);
if (count($keys)) {
$index_count = count($array[$keys[0]]);
$myArray = array();
for ($i = 0; $i < $index_count; $i++) {
$temp = array();
foreach($keys as $key) {
$temp[$key] = $array[$key][$i];
}
$myArray[] = $temp;
}
}
A different take, but here's what I would do - step by step:
First, let's get the keys - we'll be needing them a lot:
$result = array();//<-- this is the result array
$keys = array_keys($array);
Then, I'd get an empty, template array (somewhat like a model object)
$base = array_fill_keys($keys,array());
//array('username'=>array,'id'=>array(),...
Then, use that to build your result array:
$result = array_fill(0,count($array['username']),$base);
//In one-liner format, it looks like this:
$result = array_fill(0,count($array['username']),array_fill_keys(array_keys($array),array()));
//Works, but is messy as f***
Then just fill the lot, this is where that $keys variable pays off:
$length = count($result);
while ($key = array_shift($keys))
{
for ($i=0;$i<$length;$i++)
{
$result[$i][$key] = $array[$key][$i];
}
}
Note that I prefer using a while loop, as it is cleaner and (marginally) faster. Cleaner because that $keys array is being emptied as you go along. If you're working with substantial amounts of data it can sometimes make a difference. If the dataset is REALLY large, and the code has been thoroughly tested, you might even want to consider shifting from the source array (as it contains all data, it's a lot bigger than a an array containing just the keys):
while ($vals = array_shift($array))
{
$key = array_shift($keys);//<-- keep track of what array has been shifted
for ($i=0;$i<$length;$i++)
{
$result[$i][$key] = $vals[$i];
}
}
This neatly cleans up the source array, and the keys. I've tested this last approach on my server, writecodeonline and codepad, all with exactly the same results:
$foo = array('bar'=>array_fill(0,2,'ás'),'quar'=>range('a','z'));
$keys = array_keys($foo);
while($vals = array_shift($foo))
{
$key = array_shift($keys);
echo $key.' contains: => '.implode(', ',$vals).'<br/>';
}
bar contains: => ás, ás
quar contains: => a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z

How to combine both array and insert into database php

if only one array is there for example
$values = array(x, y, z);
i am adding them into database like this
foreach ($values as $value)
{
$insertFunction = addValues($value);
}
my arrays:
$array1 = Array ( 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 );
$array2 = Array ( fb1, or1, fb2, or2, fb3, or3, fb4, or4, fb5, or5 );
But i want both array to combine and insert them into database.
How can i do this please help me
Updated:
When i am printing the POST values i am getting out put like this
Array ( [0] => 1 [1] => 2 [2] => 1 [3] => 2 [4] => 1 [5] => 2 [6] => 1 [7] => 2 [8] => 1 [9] => 2 )
Array ( [0] => fb1 [1] => or1 [2] => fb2 [3] => or2 [4] => fb3 [5] => or3 [6] => fb4 [7] => or4 [8] => fb5 [9] => or5 )
when i tried with array_merge my out put is like this
Array ( [0] => 1 [1] => 2 [2] => 1 [3] => 2 [4] => 1 [5] => 2 [6] => 1 [7] => 2 [8] => 1 [9] => 2 [10] => fb1 [11] => or1 [12] => fb2 [13] => or2 [14] => fb3 [15] => or3 [16] => fb4 [17] => or4 [18] => fb5 [19] => or5 )
How to insert them in separate columns in a table $array1 and $array2
my database table is like this
1.id
2.username
3.network_id
id is primary key
network_id values coming in array1
username values coming in array2
EDIT:
After you mentioned seperated columns I think I understand what you're looking for:
I'm assuming that array1 and array2 are in the same size.
for($i = 0; $i < count($array1); $i++)
{
$array2[$i] = (int)$array2[$i]; //"validating" the username (an integer)
mysql_query("INSERT INTO yourTableName (`username`,`network_id`) VALUES('".$array2[$i]."','".$array1[$i]."')");
}
Result:
tblName:
username: 1 2 1 ...
network_id: fb1 or1 fb2 ...
Is that what you were looking for?
Ignore this and merging:
$combined = array_merge($array1 , $array2);
//$combined = Array ( 1, 2, 1, 2, 1, 2, 1, 2, 1, 2,fb1, or1, fb2, or2, fb3, or3, fb4, or4, fb5, or5 );
I think you need array_merge.
You can use array_merge(), function to merge multiple array into one.
$arrays = array_merge($array1 , $array2);
foreach ($arrays as $value)
{
$insertFunction = addValues($value);
}
If you want associate an element from array a to an element from array b, you have to use array_combine() function.
$arrays = array_combine($array1,$array2);
foreach ($array as $aValue)
{
$insertFunction = addValues($aValue);
}

Array sorting question

So I have an array such as this one:
Array
(
[-1] => Array
(
[3] => 3
[1] => 1
[6] => 6
[7] => 7
[5] => 5
)
)
It also contains some other keys that should not be modified.
I'd like to the numbers which are in a second array to come first (in the order of that second array), and then will be the numbers that don't exist in the second array, if any.
So for that matter, the second array would be:
Array
(
[0] => 6
[1] => 5
[2] => 3
)
And the final array should be as follows (please remember, there are some more keys inside of that array that should stay as they are):
Array
(
[-1] => Array
(
[6] => 6
[5] => 5
[3] => 3
[1] => 1
[7] => 7
)
)
Any ideas how that can be done?
Thanks!
It's not and shouldn't be termed as sorting but may be this code snippet may help you do what you want to:
$a1 = Array ( [-1] => Array ( [3] => 3 [1] => 1 [6] => 6 [7] => 7 [5] => 5 ) );
$a2 = Array ( [0] => 6 [1] => 5 [2] => 3 );
$sorted = getSortedArray($a1[-1] , $array2);
function getSortedArray($array1 , $array2){
$temp = Array();
$count = 0;
$totalKeys = sizeof($array2);
for($i=0;$i<sizeof($array2);$i++){
$temp[i] = $array1[$array2[i]];
unset($array1[$array2[i]]);
}
while($count!=sizeof($array1))
$temp[$totalKeys++] = $array1[$count++];
return $temp;
}
I believe the function you're looking for is called array_multisort().
array_multisort() can be used to sort
several arrays at once, or a
multi-dimensional array by one or more
dimensions.

Categories