Convert Multidimensional Array into Single Array

Convert multidimensional array into single array

Assuming this array may or may not be redundantly nested and you're unsure of how deep it goes, this should flatten it for you:

function array_flatten($array) { 
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
}
else {
$result[$key] = $value;
}
}
return $result;
}

How to convert a Single Array into a multidimensional array in PHP?

$array = array(
98 => array(
'City' => 'Caracas',
'Country' => 'Venezuela',
'Continent' => 'Latin America',
),
99 => array(
'City' => 'Cairo',
'Country' => 'Egypt',
'Continent' => 'Middle East',
),
105 => array(
'City' => 'Abu Dhabi',
'Country' => 'United Arab Emirates',
'Continent' => 'Middle East',
),
106 => array(
'City' => 'Dubai',
'Country' => 'United Arab Emirates',
'Continent' => 'Middle East',
),
107 => array(
'City' => 'Montreal',
'Country' => 'Canada',
'Continent' => 'North America',
)
);

$newArray = array();
foreach ($array as $row)
{
$newArray[$row['Continent']][$row['Country']][] = $row['City'];
}

print_r($newArray);

Convert multidimensional array to list of single array

You can convert 2d array into jagged array and then convert it to List.

int[,] arr = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };

int[][] jagged = new int[arr.GetLength(0)][];

for (int i = 0; i < arr.GetLength(0); i++)
{
jagged[i] = new int[arr.GetLength(1)];
for (int j = 0; j < arr.GetLength(1); j++)
{
jagged[i][j] = arr[i, j];
}
}

List<int[]> list = jagged.ToList();

Convert Multidimensional array to single array in codeigniter php

Try foreach loop then array_merge()

$result = [];

foreach ($array as $value) {
$result = array_merge($result, $value);
}

var_dump($result);

Convert multidimensional array into single array in PHP

Try pushing the values onto a single array in your foreach loop:

$array2 = [];
foreach ($links as $link) {
$result_url = $link->getAttribute('href');

if (!preg_match('/^https?:\/\//', $result_url)) {
$result_url = $source_url . preg_replace('/^\//', '', $result_url);
}

$array2[] = $result_url;
}
print_r($array2);

ruby convert multidimensional array into one array

You could do something like this:

arr = [[["/path/element1", false], 7], [[4, true], 5], [["/path/element6", false], 1]]
arr.map { |k,v| [*k,v] }
#=> [["/path/element1", false, 7], [4, true, 5], ["/path/element6", false, 1]]


Related Topics



Leave a reply



Submit