This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 2 years ago.
I'm looking to find a way to merge all child arrays into one large array.
array (
[0] =
[0] = '0ARRAY',
[1] = '1ARRAY'
[1] =
[0] = '2ARRAY',
[1] = '3ARRAY'
)
into
array (
[0] = '0ARRAY', [1] = '1ARRAY', [2] = '2ARRAY', [3] = '3ARRAY'
)
Without using array_merge($array[0],$array[1]) because I don't know how many arrays there actually are. So I wouldn't be able to specify them.
Thanks
If I understood your question:
php 5.6+
$array = array(
array('first', 'second'),
array('next', 'more')
);
$newArray = array_merge(...$array);
Outputs:
array(4) { [0]=> string(5) "first" [1]=> string(6) "second" [2]=> string(4) "next" [3]=> string(4) "more" }
Example: http://3v4l.org/KA5J1#v560
php < 5.6
$newArray = call_user_func_array('array_merge', $array);
If it's only two levels of array, you can use
$result = call_user_func_array('array_merge', $array);
which should work as long as $array isn't completely empty
$new_array = array();
foreach($main_array as $ma){
if(!empty($ma)){
foreach($ma as $a){
array_push($new_array, $a);
}
}
}
You can try it by placing these values:
$main_array[0][0] = '1';
$main_array[0][1] = '2';
$main_array[1][0] = '3';
$main_array[1][1] = '4';
OUTPUT:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
Related
Whilst trying to transform multiple objects and put them into one array I unfortunately get a array-in-array result.
The objects I would like to transform:
array(2) {
[0]=>
object(stdClass)#104 (1) {
["name"]=>
string(4) "Paul"
}
[1]=>
object(stdClass)#105 (1) {
["name"]=>
string(5) "Jenna"
}
}
My PHP:
for ($i=0; $i < count($readers) ; $i++) {
$json = json_encode($readers[$i]); // 1
$data = json_decode($json, TRUE); // 2
$arr = array();
array_push($arr, $data); // 3
}
The outputs:
// 1
{"name":"Paul"}{"name":"Jenna"}
-
// 2
Array
(
[name] => Paul
)
Array
(
[name] => Jenna
)
-
// 3
Array
(
[0] => Array
(
[name] => Paul
)
)
Array
(
[0] => Array
(
[name] => Jenna
)
)
Desired Outcome
I would like to have everything merged into one array. The key is the index and the value is the name.
Array
(
[0] => Paul
[1] => Jenna
)
Loop through the array of objects ($arr) and compile the final array ($finArr) with the $val->string value. Try this:
$finArr = array();
foreach ($arr as $key => $val) {
$finArr[] = $val->string;
}
You can simply iterate through the array of readers, pull out the name of each reader, and add each of their names to a numerically indexed array as you desire.
$names = array(); // Initialize.
foreach($readers as $reader) {
if (!empty($reader->name)) {
$names[] = $reader->name;
}
}
print_r($names); // To see what you've got.
Array
(
[0] => Paul
[1] => Jenna
)
You have to extract key also from array. And declare $arr = array() outside foreach
$arr = array();
for ($i=0; $i < count($readers) ; $i++) {
$data = $readers[$i]->name; //change this line
array_push($arr, $data); // 3
}
print_r($arr);
Another way is you can simply use array_column()
$arr = array_column($readers,"name");
print_r($arr);
For example
[Nationality_1] string(8)=>Indian [Nationality_5] string(12)=>American [Nationality_12] string(17)=>Japanese
I got these array values by foreach loop but I want to put these value to single array by index on strings
Desired output
[Nationality] [0] string(8)=>Indian [1] string(12)=>American[2]string(17)=>Japanese
I have tried array_values but output Null
I tried this but creates duplicate array in loop for multiple orders Please help me on it . Thanks
$Nationality[] = $value;
One solution is below code:
$nationality = array(
'Nationality_1' => 'Indian',
'Nationality_2' => 'American',
'Nationality_3' => 'Japanese'
);
$temp = array();
foreach ($nationality as $val) {
$temp[] = $val;
}
$nationality = $temp;
print_r($nationality);
unset($temp);
// Array ( [0] => Indian [1] => American [2] => Japanese )
It sounds like you may want to use array_values to pull all the nationalities from your input list.
array_values
Return all the values of an array
http://php.net/array_values
What you do with that is then up to you but from your desired output it seems you want them under another array with a "Nationality" key?
Here is an example...
$input = array(
'Nationality_1' => 'Indian',
'Nationality_5' => 'American',
'Nationality_12' => 'Japanese'
);
$output = array('Nationality' => array_values($input));
var_dump($output);
/*
array(1) {
["Nationality"]=>
array(3) {
[0]=>
string(6) "Indian"
[1]=>
string(8) "American"
[2]=>
string(8) "Japanese"
}
}
*/
See the code in action: https://eval.in/869938
This question already has answers here:
How to remove duplicate values from a multi-dimensional array in PHP
(18 answers)
How to remove duplicate values from an array in PHP
(27 answers)
Closed 9 years ago.
First i will like to say that, i have looked into other post but failed trying to accomplish my needs. I have used array_unique($array) but the duplicates don't get discarded. This is a view of my array using var_dump:
{
[0]=>
string(12) "44.94.192.40"
}
array(1) {
[0]=>
string(12) "44.94.192.41"
}
array(1) {
[0]=>
string(9) "44.94.1.1"
}
array(1) {
[0]=>
string(9) "44.94.1.1"
}
array(1) {
[0]=>
string(13) "44.96.253.100"
}
"44.94.1.1" is a duplicate which i hope to remove but i can't. Does this have to do with my array structure ?
Edited in response to your comment:
From the documentation on array_unique():
Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.
So the fact that each of your values is an array is interfering.
Try creating an array containing just the string values:
$new_array = array();
foreach ($array as $value) {
$new_array[] = $value[0];
}
$new_array = array_unique($new_array);
You can flatten your array and do array unique or do array_map with a reference to a foreign array
<?php
$data = array(
array("44.94.192.40"),
array("44.94.192.41"),
array("44.94.1.1"),
array("44.94.1.1"),
array("44.96.253.100"),
);
$visited = array();
array_map(function($v) use ( &$visited ){
if(array_search( $v[0], $visited ) === false){
$visited[] = $v[0];
};
},$data);
var_dump($visited);
array(4) {
[0]=>
string(12) "44.94.192.40"
[1]=>
string(12) "44.94.192.41"
[2]=>
string(9) "44.94.1.1"
[3]=>
string(13) "44.96.253.100"
}
You can find a variety of ways to remove duplicates from a multidimensional array on the php doc page of array_unique in the user comments
http://us3.php.net/array_unique
Orel also mentioned a duplicate question that at a glance also contains a function for doing the same
How to remove duplicate values from an array in PHP
For simplicity I have picked one for you, but depending on exactly what you want, there are many different flavors on the php page I linked
foreach ($arrAddressList AS $key => $arrAddress) {
$arrAddressList[$key] = serialize($arrAddress);
}
$arrAddressList = array_unique($arrAdressList);
foreach ($arrAddressList AS $key => $strAddress) {
$arrAddressList[$key] = unserialize($strAddress);
}
You can do it with a foreach loop
$array = array(
array("44.94.192.40"),
array("44.94.192.41"),
array("44.94.1.1"),
array("44.94.1.1"),
array("44.96.253.100"),
);
$temp_arr=array();
foreach($array as $elementKey => $element)
{
foreach($element as $valueKey => $value)
{
if(in_array($value,$temp_arr)) unset($array[$elementKey]);
else $temp_arr[]=$value;
}
}
print_r($array);
Output would be:
Array ( [0] => Array ( [0] => 44.94.192.40 ) [1] => Array ( [0] => 44.94.192.41 ) [2] => Array ( [0] => 44.94.1.1 ) [4] => Array ( [0] => 44.96.253.100 ) )
I have two arrays in php as shown in the code
<?php
$a=array('0'=>array('500'=>'1','502'=>'2'));
$b=array('0'=>array('503'=>'3','504'=>'5'));
print_r(array_merge($a[0],$b[0]));
?>
I need to merge two arrays. array_merge function successfully merged two of them but key value gets changed. I need the following output
Array
(
[0]=>Array(
[500] => 1
[502] => 2
[503] => 3
[504] => 5
)
)
What function can I use in php so that the following output is obtained without changing key values?
From the documentation, Example #3:
If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator:
<?php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
var_dump($result);
?>
The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key's element from the second array will be ignored.
array(5) {
[0]=>
string(6) "zero_a"
[2]=>
string(5) "two_a"
[3]=>
string(7) "three_a"
[1]=>
string(5) "one_b"
[4]=>
string(6) "four_b"
}
Therefore, try: $a[0] + $b[0]
$a=array('0'=>array('500'=>'1','502'=>'2'));
$b=array('0'=>array('503'=>'3','504'=>'5'));
$c = $a + $b; //$c will be a merged array
see the answer for this question
Try:
$final = array();
$a=array('0'=>array('500'=>'1','502'=>'2'));
$b=array('0'=>array('503'=>'3','504'=>'5'));
foreach( $a as $key=>$each ){
$final[$key] = $each;
}
foreach( $b as $key=>$each ){
$final[$key] = $each;
}
print_r( $final );
$a=array('0'=>array('500'=>'1','502'=>'2'));
$b=array('0'=>array('503'=>'3','504'=>'5'));
$c = $a[0] + $b[0];
print_r($c);
Will print:
Array ( [500] => 1 [502] => 2 [503] => 3 [504] => 5 )
Just write :
<?php
$a = array(2=>'green', 4=>'red', 7=>'yellow',3=>'Green');
$b = array(8=>'avocado');
$d = $a+$b;
echo'<pre>'; print_r($d);
?>
out put :
Array
(
[2] => green
[4] => red
[7] => yellow
[3] => Green
[8] => avocado
)
This question already has answers here:
Convert a comma-delimited string into array of integers?
(17 answers)
Closed 9 years ago.
Say I have a string like so $thestring = "1,2,3,8,2".
If I explode(',', $thestring) it, I get an array of strings. How do I explode it to an array of integers instead?
array_map also could be used:
$s = "1,2,3,8,2";
$ints = array_map('intval', explode(',', $s ));
var_dump( $ints );
Output:
array(5) {
[0]=> int(1)
[1]=> int(2)
[2]=> int(3)
[3]=> int(8)
[4]=> int(2)
}
Example codepad.
Use something like this:
$data = explode( ',', $thestring );
array_walk( $data, 'intval' );
http://php.net/manual/en/function.array-walk.php
For the most part you shouldn't really need to (PHP is generally good with handling casting strings and floats/ints), but if it is absolutely necessary, you can array_walk with intval or floatval:
$arr = explode(',','1,2,3');
// use floatval if you think you are going to have decimals
array_walk($arr,'intval');
print_r($arr);
Array
(
[0] => 1
[1] => 2
[2] => 3
)
If you need something a bit more verbose, you can also look into settype:
$arr = explode(",","1,2,3");
function fn(&$a){settype($a,"int");}
array_walk($f,"fn");
print_r($f);
Array
(
[0] => 1
[1] => 2
[2] => 3
)
That could be particularly useful if you're trying to cast dynamically:
class Converter {
public $type = 'int';
public function cast(&$val){ settype($val, $this->type); }
}
$c = new Converter();
$arr = explode(",","1,2,3,0");
array_walk($arr,array($c, 'cast'));
print_r($arr);
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 0
)
// now using a bool
$c->type = 'bool';
$arr = explode(",","1,2,3,0");
array_walk($arr,array($c, 'cast'));
var_dump($arr); // using var_dump because the output is clearer.
array(4) {
[0]=>
bool(true)
[1]=>
bool(true)
[2]=>
bool(true)
[3]=>
bool(false)
}
Since $thestring is an string then you will get an array of strings.
Just add (int) in front of the exploded values.
Or use the array_walk function:
$arr = explode(',', $thestring);
array_walk($arr, 'intval');
$thestring = "1,2,3,8,a,b,2";
$newArray = array();
$theArray = explode(",", $thestring);
print_r($theArray);
foreach ($theArray as $theData) {
if (is_numeric($theData)) {
$newArray[] = $theData;
}
}
print_r($newArray);
// Output
Original array
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 8 [4] => a [5] => b [6] => 2 )
Numeric only array
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 8 [4] => 2 )
$arr=explode(',', $thestring);
$newstr = '';
foreach($arr as $key=>$val){
$newstr .= $val;
}