converting different indexes values in arrays to another array in php - php

I have an array as:
Array
(
[0] => Array
(
[0] => A
[1] => B
)
[1] => C
[2] => Array
(
[0] => D
[0] => E
)
)
and I want to convert it like:
Array
(
[0] => Array
[0] => A
[1] => B
[2] => C
[3] => D
[4] => E
)
i.e I want all the values in the first array (irrespective of their indexes) to be aligned in the second array.

You need to write a custom script which merge arrays by your logic.
Example:
<?php
$a = [
['A', 'B'],
'C',
['D', 'E']
];
$result = [];
foreach ($a as $v) {
if (is_array($v))
$result = array_merge($result, $v);
else
$result[] = $v;
}
print_r([$result]);

You can user this :
$array = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)),0);
I have copied from here how Turning multidimensional array into one-dimensional array

Please try with below code:
$arr = array(
0 => array("A", "B"),
1 => "C",
2 => array("D", "E"),
);
$result = array();
$response = arrayIndex($arr, $result);
function arrayIndex($arr, $result){
foreach ($arr as $key => $value) {
if(is_array($value)){
$result = $this->arrayIndex($value, $result);
} else {
array_push($result, $value);
}
}
return $result;
}
NOTE: This function will convert n level of array elements into a single level array.

Related

How can I extract values from an array (array_values isn't working)?

I have the following PHP array
[1] => Array
(
[0] => 9780881220766
[1] => 0881220760
)
[2] => Array
(
[0] => 9780141374284
[1] => 0141374284
)
[3] => Array
(
[0] => 057305133X
[1] => 9780573051333
))
I would like the output to be as follows:
[0] => 9780881220766
[1] => 0881220760
[2] => 9780141374284
[3] => 0141374284
[4] => 057305133X
[5] => 9780573051333
I tried using array_values but I'm not getting any output.
I also tried to extract the values using a foreach loop:
foreach ($rawIsbns as $isbnKey => $isbnValue){
$formattedIsbns[] = $isbnValue;
}
However, I'm not managing.
$a = array();
foreach ($array as $tmp) {
if (is_array($tmp)) $a = array_merge($a, $tmp);
}
Created this function that allows you to merge 1 or more arrays together into the format you asked for:
function sortarr(...$arr){
$tmparr = [];
foreach($arr as $aa) foreach($aa as $a) $tmparr = array_merge($tmparr, $a);
return $tmparr;
}
Example Usage:
<?php
# First array provided
$array = array(
[
"9780881220766",
"0881220760"
],
[
"9780141374284",
"0141374284"
],
[
"057305133X",
"9780573051333"
]
);
# Second array just to show how you can input more than 1 array into the function
$array2 = array(
[
"6234808972234",
"67834757"
],
[
"0287568924344234",
"234690543"
],
[
"34565786978099x",
"3569876546"
]
);
function sortarr(...$arr){
# Declare our temp array
$tmparr = [];
# Iterates through each of the arrays inside the array(s) provided
foreach($arr as $aa) foreach($aa as $a) $tmparr = array_merge($tmparr, $a);
# Return the results
return $tmparr;
}
print_r( sortarr($array, $array2) );
Results:
Array
(
[0] => 9780881220766
[1] => 0881220760
[2] => 9780141374284
[3] => 0141374284
[4] => 057305133X
[5] => 9780573051333
[6] => 6234808972234
[7] => 67834757
[8] => 0287568924344234
[9] => 234690543
[10] => 34565786978099X
[11] => 3569876546
)
Live Demo: http://sandbox.onlinephpfunctions.com/code/838a108498f446ae4a5f8e42fa441ec11941c567
I managed to solve the problem by initializing an array and adding values of subsequent nested arrays using array_push
function isbns($rawIsbns) {
$prevArrayValues = null;
foreach ($rawIsbns as $value) {
if (!isset($prevArrayValues)) {
$prevArrayValues = []; //initiallise first value unless initialized
}
if (empty($value)) {
$return = []; //disregard empty values
} else {
$return = $value; // add arrays to existing array
}
$prevArrayValues = array_merge($prevArrayValues, $return);
}
return $prevArrayValues;
}

PHP array_merge_recursive using foreach loop

I want to merge a few array into a new array, but group them by the same key value
When I use this loop
foreach($mrh as $group){
print_r($group);
};
Out put is
Array (
[2] => 4
)
Array (
[2] => 5
)
Array (
[3] => 7
)
Array (
[3] => 8
)
Array (
[3] => 10
)
My desired output is
array (
[2] => array(
[0] => 4,
[1] => 5
),
[3] => array(
[0] => 7,
[1] => 8,
[2] => 10,
)
)
array_merge_recursive() may be useful, but i cant solve it with an foreach loop
Simply loop the array, and with an inner loop, process the inner elements. Then assign them into the resulting array based on their key.
$result = [];
foreach ($mrh as $group) {
foreach ($group as $key=>$value) {
// Declare the array if it does not exist, to avoid notices
if (!isset($result[$key]))
$result[$key] = [];
// Append the value
$result[$key][] = $value;
}
}
Live demo at https://3v4l.org/NeECu
If your inner array is always on size 1 you can use array-key-first as:
foreach($mrh as $e) {
$k = array_key_first($e);
$res[$k][] = $e[$k];
}
Live example: 3v4l
$mrh = [ [2=>4], [2=>5], [3=>7], [3=>8], [3=>10] ];
$newArray = [];
foreach($mrh as $group){ // loop over groups
foreach($group as $key => $value) { // “loop over” group, to get access to key and value
$newArray[$key][] = $value; // add value as a new element in the sub-array accessed by $key
}
}
using foreach
$a = [
[2 => 4],
[2 => 5],
[3 => 7],
[3 => 8],
[3 => 10]
];
$r = [];
foreach($a as $k => $v){
$_value = end($v);
$r[key($v)][] = $_value;
}
echo '<pre>';
print_r($r);

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);

Put in array the result from arsort array with fatser method

How can I put in array the result from arsort array with faster method ?
I have this :
Array
(
[a] => 32389
[o] => 25534
)
I would like this :
Array
(
[1] => array
([0] => 'a',
[1] => '32389')
[2] => array
([0] => 'o',
[1] => '25534')
)
I do this :
$words = [];
foreach($words as $key=>$value) {
$words[] = [$k, $v];
}
It works, but after my arsort, I would like if (foreach($words as $key => $value) is the better/faster method to execute this task or if there is an other method/function with php ?
Easy to do:-
<?php
$data = Array
(
'a' => 32389,
'o' => 25534
);
$new_data = array();
foreach ($data as $key=>$value){ // iterate through your original array
$new_data[] = array($key,$value); // assign key and value array to new array
}
echo "<pre/>";print_r($new_data); // print new array
?>
output:- https://eval.in/556504
Based on your question this is the best solution (every one else also use same things). Also there is no matter of speed in the above loop working.
$a = [ 'a' => 32389, 'o' => 25534 ];
$b = [];
foreach($a as $k => $v) {
$b[] = [$k, $v];
}
print_r($b);
Output:
Array
(
[0] => Array
(
[0] => a
[1] => 32389
)
[1] => Array
(
[0] => o
[1] => 25534
)
)
<?php
$array = array('a' => 32389, 'o' => 25534);
$result = array();
foreach($array as $k => $v) {
$result[] = array($k, $v);
}
var_dump($result);
?>
Eval.in
Check that out.
Your code is nearly there.
$words_extract = array(
'a' => 32389,
'o' => 25534
);
$words = array();
foreach($words_extract as $k => $v) {
$words[] = array($k, $v);
}

PHP Multidimensional array merge two trees inside an array How to?

I want to merge two trees, in a multidimensional to one tree in the md array in php:
$array[1] = Array
[0] => a
[1] => b
[2] => c
$array[2] = Array
[0] => d
[1] => e
[2] => f
result:
$array[1] = Array
[0] => ad
[1] => be
[2] => cf
You could try this:
<?php
foreach($array[1] as $key => $value)
{
$array[1][$key] = $value.$array[2][$key];
}
?>
We can use array function to solve this Problem Like this :
$array = array('a','b','c');
$array2 = array('d','e','f');
$c = array_combine($array, $array2);
foreach($c as $key=>$value){
$data[] = $key.$value;
}
print_r($data);

Categories