Converting PHP Array of Arrays into Single Array

Converting php array of arrays into single array

Since PHP 5.5.0 there is a built-in function array_column which does exactly this.

Best way to Convert array of arrays into single array

With call_user_func_array function:

$array_of_arrays = [[1,2,3],[4,5,6],[7,8],[9,10]];
$result = call_user_func_array("array_merge", $array_of_arrays);
print_r($result);

The output:

Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
)

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

array of arrays to array of objects php

EDIT for specific object:

To adhere to your existing style as close as possible without messing with array_map voodoo:

class Assoc {
public function setObject($assoc) {
foreach ($assoc as $arr) {
$this->assoc[] = new Obj($arr);
}
}
}
class Obj {
public function __construct($item) {
foreach ( $item as $property=>$value ) {
$this->{$property} = $value;
}
}
}

$test = New Assoc();
$test->setObject($assoc);

Original:

If you just need generic conversion, and not into specific custom objects (not exactly clear in your post?) you can try this:

$new_array = array();
foreach ($assoc as $to_obj)
{
$new_array[] = (object)$to_obj;
}

// Print results
var_dump($new_array);

outputs:

array(2) {
[0]=>
object(stdClass)#1 (2) {
["prop1"]=>
string(4) "val1"
["prop2"]=>
string(4) "val2"
}
[1]=>
object(stdClass)#2 (2) {
["prop1"]=>
string(4) "val1"
["prop2"]=>
string(4) "val2"
}
}

How to Flatten a Multidimensional Array?

You can use the Standard PHP Library (SPL) to "hide" the recursion.

$a = array(1,2,array(3,4, array(5,6,7), 8), 9);
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($a));
foreach($it as $v) {
echo $v, " ";
}

prints

1 2 3 4 5 6 7 8 9 

PHP: convert array with multiple arrays to one single associative array

You can simply use array_column

$arr = array ( 0 => array ( 'name' => 'firstname', 'value' => 'Max', ), 1 => array ( 'name' => 'lastname', 'value' => 'Smith ', ), 2 => array ( 'name' => 'age', 'value' => 12, ), 3 => array ( 'name' => 'gender', 'value' => 'male', ));

var_dump(array_column($arr, "value", "name"));

Result:

array(4) {
["firstname"]=>
string(3) "Max"
["lastname"]=>
string(6) "Smith "
["age"]=>
int(12)
["gender"]=>
string(4) "male"
}


Related Topics



Leave a reply



Submit