PHP combines 2 arrays - php

I have 2 arrays in php
$array1[] = a,b,c,d,e;
$array2[] = 1,2,3,4,5;
$data = array('letter'=>$array1,'num'=>$array2);
return json_encode($data);
This will return:
[[a,b,c,d,e],[1,2,3,4,5]]
I'd like to return it in json_encode like this:
$data = [[1a,1],[b,2],[c,3],[d,4],[e,5]];
Can someone help me with this?

this is the simplest solution
$result = array();
foreach ($array1 as $k1 => $v1) {
$result[] = array($v1, $array2[$k1]);
}
echo json_encode($result)
but arrays must have the same length and same keys

Try below code, it is flexible and don't have to care about the length of the arrays.
<?php
$letters = array('a','b','c','d','e');
$numbers = array('1','2','3','4','5');
$counter = (sizeof($letters) > sizeof($numbers)) ? sizeof($letters) : sizeof($numbers);
$arr = array();
for($i=0; $i<$counter; $i++)
{
if(array_key_exists($i, $letters))
$arr[$i][] = $letters[$i];
if(array_key_exists($i, $numbers))
$arr[$i][] = $numbers[$i];
}
$json = json_encode($arr);
echo $json;
Output:
[["a","1"],["b","2"],["c","3"],["d","4"],["e","5"]]
Demo:
http://3v4l.org/7v7X4

What you are looking for is the function array_combine().
Here is an example:
$array1 = array("a","b","c","d","e");
$array2 = array(1,2,3,4,5);
$data = array_combine($array1, $array2);
$new_data = array();
foreach($data AS $key => $value) {
$new_data[] = array($key, $value);
}
print_r(json_encode($new_data));
Which should return something like:
[["a",1],["b",2],["c",3],["d",4],["e",5]]
UPDATE Changed the code to give the result wanted...

Related

re-arrange multidimensional php array

I need to re-arrange a php multidimensional array so that to 'match' corresponding values from different arrays;
this is my reproducible example
<?php
// my original array
$myar= array(
array('A'=>'xxx','B'=>1),
array('A'=>'yyy','B'=>2),
array('A'=>'xxx','B'=>3),
array('A'=>'yyy','B'=>4)
);
print_r($myar);
// my desired result, new array
$myar_new= array(
array('xxx'=>1,'yyy'=>2),
array('xxx'=>3,'yyy'=>4)
);
print_r($myar_new);
?>
any help for that?
thanks
If I got your logic right then this function is what you need.
(Edited)
function strange_reformat($srcArray) {
$newArray = [];
$c = count($srcArray);
$i = 0;
$groupStart = null;
$collect = [];
while($i < $c) {
$row = current($srcArray[$i]);
if ($row == $groupStart) {
$newArray[] = $collect;
$collect = [];
}
$tmp = array_values($srcArray[$i]);
$collect[] = [$tmp[0] => $tmp[1]];
if ($groupStart === null) $groupStart = $row;
$i++;
}
$newArray[] = $collect;
return $newArray;
}
print_r(strange_reformat($myar));
yes, that's it...
but now I need to generalise it, please consider this case
$myar= array(
array('A'=>'xxx','B'=>1),
array('A'=>'yyy','B'=>2),
array('A'=>'zzz','B'=>5),
array('A'=>'xxx','B'=>3),
array('A'=>'yyy','B'=>4),
array('A'=>'zzz','B'=>6)
);
function strange_reformat($srcArray) {
$newArray = [];
$c = count($srcArray);
for ($i=0; $i<$c; $i+=3) {
$first = array_values($srcArray[$i]);
$second = array_values($srcArray[$i+1]);
$third = array_values($srcArray[$i+2]);
$newArray[] = [$first[0]=>$first[1], $second[0]=>$second[1], $third[0]=>$third[1]];
}
return $newArray;
}
print_r(strange_reformat($myar));

How to combine three arrays without using array_merge or array_combine in php

I want to combine three arrays into one
I am expecting like output are using array_combine or array_merge
Likes
friends,
usa,
usa2,
..,
..,
so.on..,
$array1 = array('likes', 'friends', 'USA');
$array2 = array('USA2', 'lools', 'tools');
$array3 = array('USA3', 'Awesome', 'lop');
$output = $array1+$array2+$array3;
echo "<pre>";
print_r($output);
echo "</pre>";
But here i am getting output as
likes,
friends,
USA
In PHP 5.6+ You can also use ... when calling functions to unpack an array or
Traversable variable or literal into the argument list:
$array1 = array('likes', 'friends', 'USA');
$array2 = array('USA2', 'lools', 'tools');
$array3 = array('USA3', 'Awesome', 'lop');
array_push($array1, ...$array2, ...$array3);
echo "<pre>";
print_r($array1);
echo "</pre>";
demo
check this out custom function for array push
<?php
$array1 = array('likes', 'friends', 'USA');
$array2 = array('USA2', 'lools', 'tools');
$array3 = array('USA3', 'Awesome', 'lop');
function push($array1,$array2){
$return = array();
foreach($array1 as $key => $value){
$return[] = $value;
}
foreach($array2 as $key => $value){
$return[] = $value;
}
return $return;
}
$array = push($array1,$array2);
$array = push($array,$array3);
print_r($array);
If you want to have an array of arrays, each element at a given index having the values of the three arrays at the respecting index, then:
$length = count($array1);
$result = array();
for ($index = 0; $index < $length; $index++) {
$result[]=array($array1[$index], $array2[$index], $array3[$index]);
}
If you simply want to put all items into a new array, then:
$result = array();
for ($index = 0; $index < count($array1); $index++) {
$result[]=$array1[$index];
}
for ($index = 0; $index < count($array2); $index++) {
$result[]=$array2[$index];
}
for ($index = 0; $index < count($array3); $index++) {
$result[]=$array3[$index];
}
Use Array Merge
$array1 = array('likes', 'friends', 'USA');
$array2 = array('USA2', 'lools', 'tools');
$array3 = array('USA3', 'Awesome', 'lop');
$output = array_merge($array1,$array2,$array3);
echo "<pre>";
print_r($output);
echo "</pre>";

PHP array keys as nth value

I have an Associative array as
$array = Array([0]=>a[1]=>b[2]=c[3]=>d);
I need to build an array from this array where the the first key becomes a and the value becomes b & 2nd key becomes c and value becomes d.
Output should be:
$finalarray = Array([a]=>b,[c]=>d);
I have tried this following code:
foreach($array as $key=>$value){
$arr[$value] = array_slice($array, 1, 1);
$finalarray[] = $arr;
}
Please help me with this!
The best way is to loop on your first array, but to skip one value on two:
$array = array("a", "b", "c", "d");
$finalArray = array();
for ($i = 0; $i < count($array); $i+=2) {
$finalArray[$array[$i]] = $array[$i + 1];
}
This may help:
$a = array('a','b','c','d'); $b = array();
$length = count(a)%2 ? count($a)-1 : count($a);
for($i=0; $i<$length; $i++){
$b[$a[$i]] = $a[++$i];
}
var_dump($a,$b);
Little changed your code:
$i=0;
foreach($array as $key=>$value){
$value_2=$value++;
if($i%2==0)
$arr[$value_2] =$value;
$i++;
//$finalarray[] = $arr;
}
echo"<pre>";
print_r($arr);
If your array is associative , below code may help you
<?php
$array = array(0=>'a',1=>'b',2=>'c',3=>'d');
$new_array = array();
for($i=0;$i<count($array);$i+=2)
{
$new_array[$array[$i]] = $array[$i+1];
}
print_r($new_array);
?>

PHP Merging arrays with for loops without using array_merge function

I am learning more about for loops and would like to see how do you merge arrays using only for loops and not using built-in PHP functions such as array_merge().
I know you can use foreach to do this, but how would this work using only for loops and not foreach?
foreach example:
$array1 = ['judas', 'john', 'michael'];
$array2 = ['fernando', 'jsamine', 'sam', 'walter'];
$array3 = ['judas', 'john', 'mike', 'steve'];
foreach ([$array1, $array2, $array3] as $arr) {
foreach ($arr as $values) {
...
}
}
Yes, you can do this using just for loops.
$array1 = ['judas', 'john', 'michael'];
$array2 = ['fernando', 'jsamine', 'sam', 'walter'];
$array3 = ['judas', 'john', 'mike', 'steve'];
$all_arrays = [$array1, $array2, $array3];
$merged = [];
for ($i = 0; $i < 3; $i++) {
$arr = $all_arrays[$i];
$x = count($arr);
for ($j=0; $j < $x; $j++) {
// Using the value as the key in the merged array ensures
// that you will end up with distinct values.
$merged[$arr[$j]] = 1;
}
}
// You could use array_keys() to do get the final result, but if you
// want to use just loops then it would work like this:
$final = [];
$x = count($merged);
for ($i=0; $i < $x; $i++) {
$final[] = key($merged);
next($merged);
}
var_dump($final);
key() and next() ARE php functions. But I really do not know of a way to get to the keys without using either foreach or some php function.
Iterate each array on its own:
foreach($array2 as $v)
if(!in_array($v, $array1))
$array1[] = $v;
foreach($array3 as $v)
if(!in_array($v, $array1))
$array1[] = $v;
Or simply use array_merge() - there is no reason for do not do it.
$a=array('1','2','3','4','5');
$b=array('a','b','c','d','e');
$c=count($b);
for($i=0; $i<$c; $i++)
{
$a[]=$b[$i]; // each element 1 by 1 store inside the array $a[]
}
print_r($a);
function arrayMerge(array $arrays) {
$mergeArray = [];
foreach ($arrays as $key => $array) {
foreach($array as $finalArray) {
$mergeArray[] = $finalArray;
}
}
return $mergeArray;
}
$array1 = [
'Laravel', 'Codeigniter', 'Zend'
];
$array2 = [
'Node js', 'Vue js', 'Angular js'
];
$array3 = [
'Python', 'Django', 'Ruby'
];
print_r(arrayMerge([$array1, $array2, $array3]));
$arr1 = array(1,2,3,4,5);
$arr2 = array(2,5,6,7,8);
$allval = array();
foreach($arr2 as $key=>$val){
$arr1[] = $val;
}
foreach($arr1 as $k=>$v){
if(!in_array($v,$allval)){
$allval[] = $v;
}
}
echo "<pre>"; print_R($allval);

How to convert every two consecutive values of an array into a key/value pair?

I have an array like the following:
array('category_name:', 'c1', 'types:', 't1')
I want the alternate values of an array to be the values of an array:
array('category_name:' => 'c1', 'types:' => 't1')
You could try: (untested)
$data = Array("category_name:","c1","types:","t1"); //your data goes here
for($i=0, $output = Array(), $max=sizeof($data); $i<$max; $i+=2) {
$key = $data[$i];
$value = $data[$i+1];
$output[$key] = $value;
}
Alternatively: (untested)
$output = Array();
foreach($data as $key => $value):
if($key % 2 > 0) { //every second item
$index = $data[$key-1];
$output[$index] = $value;
}
endforeach;
function fold($a) {
return $a
? array(array_shift($a) => array_shift($a))
+ fold($a)
: array();
}
print_r(fold(range('a','p' )));
~)
upd: a real-life version
function fold2($a) {
$r = array();
for($n = 1; $n < count($a); $n += 2)
$r[$a[$n - 1]] = $a[$n];
return $r;
}
Here is another yet complex solution:
$keys = array_intersect_key($arr, array_flip(range(0, count($arr)-1, 2)));
$values = array_intersect_key($arr, array_flip(range(1, count($arr)-1, 2)));
$arr = array_combine($keys, $values);
$array = your array;
$newArray['category_name:'] = $array[1];
$newArray['types:'] = $array[3];

Categories