Convert Multidimensional array to single array in php [duplicate] - php

This question already has answers here:
Convert multidimensional array into single array [duplicate]
(24 answers)
Closed 5 years ago.
It's probably beginner question but I'm going through documentation for
longer time already and I can't find any solution and i have an array which
is multidimensional given below format.
/* This is how my array is currently */
Array
(
[0] => Array
(
[0] => Array
(
[title] => a
[title_num] =>1
[status] => 1
)
[1] => Array
(
[title] => Mr
[title_num] => 82
[status] => 1
)
)
[1] => Array
(
[0] => Array
(
[title] => b
[title_num] =>25
[status] => 2
)
[1] => Array
(
[title] => c
[title_num] =>45
[status] => 2
)
)
)
I want to convert this array into this form
/*Now, I want to simply it down to this*/
Array
(
[0] => Array
(
[title] => a
[title_num] =>1
[status] => 1
)
[1] => Array
(
[title] => Mr
[title_num] => 82
[status] => 1
)
[2] => Array
(
[title] => b
[title_num] =>25
[status] => 2
)
[3] => Array
(
[title] => c
[title_num] =>45
[status] => 2
)
)
I have tried array_flatten,array_map PHP built in function
A link or anything to point me in the right direction will be highly
appreciated

Here is another trick to solve your problem,
function custom_filter($array) {
$temp = [];
array_walk($array, function($item,$key) use (&$temp){
foreach($item as $value)
$temp[] = $value;
});
return $temp;
}
array_walk — Apply a user supplied function to every member of an array
Here is working demo.

here you go
$result = [];
foreach($array as $arr)
{
$result = array_merge($result , $arr);
}
var_dump($result);

Like this:
$i=0;
foreach ($array as $n1) {
foreach ($n1 as $n2) {
$newArr[$i]['title']=$n2['title'];
$newArr[$i]['title_num']=$n2['title_num'];
$newArr[$i]['status']=$n2['status'];
}
$i++;
}
Or simpler as suggested in the comments
for ($i=0; $i < count($array); $i++) {
foreach ($array[$i] as $n2) {
$newArr[$i]['title']=$n2['title'];
$newArr[$i]['title_num']=$n2['title_num'];
$newArr[$i]['status']=$n2['status'];
}
}

Related

Convert nested associative array to single array in php [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 10 months ago.
I have nested array with key & value pair. i want to convert it in single array.
/* This is current array */
Array
(
[id] => Array
(
[0] => 1
[1] => 2
)
[qty] => Array
(
[0] => 1
[1] => 1
)
[price] => Array
(
[0] => 364.41
[1] => 300
)
[amount] => Array
(
[0] => 364.41
[1] => 300
)
)
/*Now, I want this type of array*/
Array
(
[0] => Array
(
[id] => 1
[qty] => 1
[price] => 364.41
[amount] => 364.41
)
[1] => Array
(
[id] => 2
[qty] => 1
[price] => 300
[amount] => 300
)
)
I have tried array_walk and some other solutions but i could not find any proper solution
Thanks in advance
Main array is your nested array and Collection is the result you want
foreach($mainArray["id"] as $key => $value ){
$collection[$key] = ['id' => $value];
foreach(array_keys($mainArray) as $arrayKeysOfmainArray){
if(!array_key_exists($arrayKeysOfmainArray, $collection)){
$collection[$key][$arrayKeysOfmainArray] = $mainArray[$arrayKeysOfmainArray][$key];
}
}
}
print_r($collection);
$mainarray['id'] = Array(1,2,3);
$mainarray['qty'] = Array(1,1,4);
$mainarray['price'] = Array(364.41,300,500);
$mainarray['amount'] = Array(364.41,300,600);
$new = [];
foreach($mainarray as $key=> $singleArray){
if(count($singleArray) > 0){
foreach($singleArray as $childKey=> $value){
$new[$childKey][$key] = $value;
}
};
}`

How to remove duplicate values from a multi dimensional array for specific key in php [duplicate]

This question already has answers here:
How to remove duplicate values from a multi-dimensional array in PHP
(18 answers)
Closed 2 years ago.
I searched for solutions on here but didn't find one for my use case.
I have a big array which is built like this example:
Array
(
[0] => Array
(
[Template] => page.html5
)
[1] => Array
(
[Template] => page2.html5
)
[2] => Array
(
[Template] => page.html5
)
[3] => Array
(
[Template] => page2.html5
)
[4] => Array
(
[Template] => page.html5
)
[5] => Array
(
[Template] => page2.html5
)
[6] => Array
(
[id] => 27
[table] => tl_custom
[type] => text
[data] => Array
(
[fragment] => example
[previewId] => 1
[isActive] => 1
)
)
)
I would like to remove all duplicate values for the array key "Template", but besides that I want the array to stay the way it is.
So afterwards my Array should look like:
Array
(
[0] => Array
(
[Template] => page.html5
)
[1] => Array
(
[Template] => page2.html5
)
[6] => Array
(
[id] => 27
[table] => tl_custom
[type] => text
[data] => Array
(
[fragment] => example
[previewId] => 1
[isActive] => 1
)
)
)
Is there a way to achieve this without using lots of memory?
Thanks for your answers :)
You could use the following logic, which uses:
array_map() to flatten the array with index keys-values, and serialize() (stringify) the last array element so we can use
array_unique() on the result.
Then, to restore the stringified array, i.e. turn it back into an array, we use unserialize().
<?php
$newArr = array_unique(array_map(function ($el) {
return $el['Template'] ?? serialize($el);
}, $arr));
// restore the last element to array
$last = array_key_last($newArr); // (PHP 7 >= 7.3.0)*
$newArr[$last] = unserialize($newArr[$last]);
*if PHP version <7.3.0 use: end($newArr); $last = key($newArr);
Output:
Array
(
[0] => page.html5
[1] => page2.html5
[6] => Array
(
[id] => 27
[table] => tl_custom
[type] => text
[data] => Array
(
[fragment] => example
[previewId] => 1
[isActive] => 1
)
)
)
working demo
The code below loops the array, marks indexes for removal and then another loop does the removals:
$templates = array(); //This will store the remove plan
for ($index = 0; $index < count($input); $index++) {
if (isset($input[$index]["Template"])) { //Ignore items where there is no template
if (isset($templates[$input[$index]["Template"]])) { //Let's check whether we have already seen this template
$templates[$input[$index]["Template"]] = array(); //From now on we will find duplicates for this dude
} else { //Mark for removal
$templates[$input[$index]["Template"]][]=$index;
}
}
}
//Actual removals
foreach($templates => $index) {
//Removing the actual element:
unset($input[$index]["Template"]);
//Remove the parent as well if it becomes empty
if (!count($input[$index])) unset($input[$index]);
}
The memory need for this algorithm is:
average(element_size) * number_of_elements

How to combine two arrays as key and value? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
In one array there are they keys and in another array there the values. I want to combine these two arrays in a manner all keys of array1 and all values of array2 as shown below. How can it be done in PHP?
Here are the two arrays
Array
(
[0] => url
[1] => downloadName
[2] => downloadType
[3] => downloadSize
[4] => url
[5] => downloadName
[6] => downloadType
[7] => downloadSize
)
Array
(
[0] => https://www.clearcube.com/support/controller/downloads.php?id=450
[1] => F6151 Media Converter System with 100 base TX to 100 base FX.pdf
[2] => Manual
[3] => 0.39
[4] => https://www.clearcube.com/support/controller/downloads.php?id=582
[5] => G0400147 Rev B.xlsx
[6] => Manual
[7] => 0.37
)
And I need in this format.
Array
(
[url] => Array(
[0] => https://www.clearcube.com/support/controller/downloads.php?id=450
[1] => https://www.clearcube.com/support/controller/downloads.php?id=582
)
[downloadName] => Array(
[0] => F6151 Media Converter System with 100 base TX to 100 base FX.pdf
[1] => G0400147 Rev B.xlsx
)
[downloadType] => Array(
[0] => Manual
[1] => Manual
)
[downloadSize] => Array(
[0] => 0.39
[1] => 0.37
)
)
With the help of array_walk() you can combine it easily.
$keys = ['url','downloadName','downloadType','downloadSize','url','downloadName','downloadType','downloadSize'];
$values = [ 'https://www.clearcube.com/support/controller/downloads.php?id=450', 'F6151 Media Converter System with 100 base TX to 100 base FX.pdf', 'Manual', 0.39, 'https://www.clearcube.com/support/controller/downloads.php?id=582', 'G0400147 Rev B.xlsx', 'Manual', 0.37 ];
$result = [];
array_walk($keys, function ($val, $key) use (&$result, $values) { $result[$val][] = $values[$key]; });
print_r($result);
Working demo.
Output:
Array
(
[url] => Array
(
[0] => https://www.clearcube.com/support/controller/downloads.php?id=450
[1] => https://www.clearcube.com/support/controller/downloads.php?id=582
)
[downloadName] => Array
(
[0] => F6151 Media Converter System with 100 base TX to 100 base FX.pdf
[1] => G0400147 Rev B.xlsx
)
[downloadType] => Array
(
[0] => Manual
[1] => Manual
)
[downloadSize] => Array
(
[0] => 0.39
[1] => 0.37
)
)
a simple way would be
$result = [];
foreach ($array1 as $key1 => $value1) {
$result[$value1][] = $array2[$key1];
}
with verification implemented and independently from the indexes
if (count($array1) == count($array2)) {
$result = [];
$i = 0;
foreach ($array1 as $value1) {
$j=0;
foreach ($array2 as $value2) {
if ($j == $i) {
$result[$value1][] = $value2;
break;
}
$j++;
}
$i++;
}
var_dump($result);
}
Suppose key array is $arr1 and data array is $arr2 then you can run following loop and create new array by following
$new_arr = []
foreach($arr1 as $key=>$arr){
$new_arr[$arr][] = $arr2[$key];
}
//final array is $new_arr
You might use an index based approach, first checking if the length of the arrays are the same.
Loop the keys from array 1 and add the values from array 2 for that key.
$result = [];
if (count($array1) === count($array2)) {
for ($i = 0; $i < count($array1); $i++) {
$result[$array1[$i]][] = $array2[$i];
}
}
print_r($result);
Php demo
Result
Array
(
[url] => Array
(
[0] => https://www.clearcube.com/support/controller/downloads.php?id=450
[1] => https://www.clearcube.com/support/controller/downloads.php?id=582
)
[downloadName] => Array
(
[0] => F6151 Media Converter System with 100 base TX to 100 base FX.pdf
[1] => G0400147 Rev B.xlsx
)
[downloadType] => Array
(
[0] => Manual
[1] => Manual
)
[downloadSize] => Array
(
[0] => 0.39
[1] => 0.37
)
)

PHP array merge issues , multilevel array merge into single level [duplicate]

This question already has answers here:
How to "flatten" a multi-dimensional array to simple one in PHP? [duplicate]
(23 answers)
Closed 5 years ago.
Here is my output: im using more foreach loop with different condition and values put into same array name $returnVal[]=
EX:
foreach($val1 as $vals)
{
$returnVal[]=$vals;
}
foreach($val2 as $vals)
{
$returnVal[]=$vals;
}
foreach($val3 as $vals)
{
$returnVal[]=$vals;
}
foreach($val4 as $vals)
{
$returnVal[]=$vals;
} `
Im getting Output:
Array
(
[0] => Array
(
[0] => 39705--COLUMBUS--LOWNDES--MS
[1] => 39702--COLUMBUS--LOWNDES--MS
[2] => 39710--COLUMBUS--LOWNDES--MS
[3] => 39701--COLUMBUS--LOWNDES--MS
)
[1] => Array
(
[0] => Array
(
[0] => 39705--COLUMBUS--LOWNDES--MS
[1] => 39702--COLUMBUS--LOWNDES--MS
[2] => 39710--COLUMBUS--LOWNDES--MS
[3] => 39701--COLUMBUS--LOWNDES--MS
)
)
[2] => Array
(
[0] => Array
(
[0] => 39705--COLUMBUS--LOWNDES--MS
[1] => 39702--COLUMBUS--LOWNDES--MS
[2] => 39710--COLUMBUS--LOWNDES--MS
[3] => 39701--COLUMBUS--LOWNDES--MS
)
[1] => Array
(
[0] => Array
(
[0] => 39705--COLUMBUS--LOWNDES--MS
[1] => 39702--COLUMBUS--LOWNDES--MS
[2] => 39710--COLUMBUS--LOWNDES--MS
[3] => 39701--COLUMBUS--LOWNDES--MS
)
)
[2] => 57038--JEFFERSON--UNION--SD
)
[3] => 57049--NORTH SIOUX CITY--UNION--SD
)
My Question: remove duplicate values and merge into one level
Push element if it is not exists in the result array, this will avoid duplicate entries. Try the code below,
$returnVal = [];
foreach($val1 as $vals)
{
if (!in_array($vals, $returnVal)) {
$returnVal[]=$vals;
}
} ..etc and so on

Group values from array

I have this array:
SimpleXMLElement Object
(
[id] => Array
(
[0] => Koala.jpg
[1] => Jellyfish.jpg
)
[desc] => Array
(
[0] => koaladesc
[1] => jelly desc
)
[qtidade] => Array
(
[0] => 1
[1] => 5
)
I need create some php function that help me group the values like this:
[0] => Array
(
[0] => Koala.jpg
[1] => koaladesc
[2] => 1
)
[1] => Array
(
[0] => Jellyfish
[1] => jelly desc
[2] => 5
)
Could anyone help me?
Something like this should do the trick, but it's localized to what you're asking based on the vagueness of your question:
$new_array = array();
foreach($simple_xml_object as $obj) {
if(is_array($obj)) {
for($i = 0; $i < count($obj); $i++) {
$new_array[$i][] = $obj[$i];
}
}
}
I would suggest looking at the documentation on the foreach() construct, as well as looking over the SimpleXML manual.
So, you want to tranpose an array. Here's a magical way of transposing rectangular arrays:
array_unshift($array, null);
$array = call_user_func_array('array_map', $array);
let's suppose your array is saved in variable $arrayValues
$arrayValues = [id] => Array
(
[0] => Koala.jpg
[1] => Jellyfish.jpg
)
[desc] => Array
(
[0] => koaladesc
[1] => jelly desc
)
[qtidade] => Array
(
[0] => 1
[1] => 5
)
now you need to create the following code:
foreach($arrayValues as $array)
{
echo $array->id;
echo $array->desc;
echo $array->qtidade;
}
this may work well for you.

Categories