How to flatten array in PHP? - php

I have an array that contains 4 arrays with one value each.
array(4) {
[0]=>
array(1) {
["email"]=>
string(19) "test01#testmail.com"
}
[1]=>
array(1) {
["email"]=>
string(19) "test02#testmail.com"
}
[2]=>
array(1) {
["email"]=>
string(19) "test03#testmail.com"
}
[3]=>
array(1) {
["email"]=>
string(19) "test04#testmail.com"
}
}
What is the best (=shortest, native PHP functions preferred) way to flatten the array so that it just contains the email addresses as values:
array(4) {
[0]=>
string(19) "test01#testmail.com"
[1]=>
string(19) "test02#testmail.com"
[2]=>
string(19) "test03#testmail.com"
[3]=>
string(19) "test04#testmail.com"
}

In PHP 5.5 you have array_column:
$plucked = array_column($yourArray, 'email');
Otherwise, go with array_map:
$plucked = array_map(function($item){ return $item['email'];}, $yourArray);

You can use a RecursiveArrayIterator . This can flatten up even multi-nested arrays.
<?php
$arr1=array(0=> array("email"=>"test01#testmail.com"),1=>array("email"=>"test02#testmail.com"),2=> array("email"=>"test03#testmail.com"),
3=>array("email"=>"test04#testmail.com"));
echo "<pre>";
$iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr1));
$new_arr = array();
foreach($iter as $v) {
$new_arr[]=$v;
}
print_r($new_arr);
OUTPUT:
Array
(
[0] => test01#testmail.com
[1] => test02#testmail.com
[2] => test03#testmail.com
[3] => test04#testmail.com
)

Related

Add array to array without key IDs? - PHP

I have a big array which looks like this:
array(2) {
["Final Fantasy VII"]=>
array(5) {
["rows"]=>
array(2) {
[0]=>
array(6) {
["price"]=>
string(5) "11.69"
["price_old"]=>
string(4) "4.66"
["currency"]=>
string(4) "euro"
["portal"]=>
string(0) ""
["link"]=>
string(77) "https://de.gamesplanet.com/game/final-fantasy-vii-download--1001-1?ref=gmkeys"
["shop"]=>
string(4) "9507"
}
[1]=>
array(6) {
["price"]=>
string(5) "14.99"
["price_old"]=>
...
}
}
}
["Battlefield 1"]=>
array(3) {
["rows"]=>
array(2) {
[0]=>
array(6) {
["price"]=>
...
}
[1]=>
array(6) {
["price"]=>
...
}
}
}
}
And I want to get only certain parts of this array where the name is matching my searched title. So, I use this code for that:
function createACFRepeater($title){
$repeater = array();
if(searchForGameXML($title)){
$count = count($GLOBALS["productsXML"][$title]['rows']);
for($i = 0; $i < $count; $i++){
array_push($repeater, $GLOBALS["productsXML"][$title]['rows'][$i]);
}
return $repeater;
}else{
return $repeater;
}
}
My problem now is that the the $repeater array looks like this:
array(2) {
[0]=>
array(6) {
["price"]=>
string(5) "19.98"
["price_old"]=>
...
}
[1]=>
array(6) {
["price"]=>
string(4) "7.99"
["price_old"]=>
...
}
}
There is a numeric key which is pointing to the array [0] => .... But what I want is simply an array in a array without any associative relations...
How can I create an array which looks like this:?
array(2) {
array(6) {
["price"]=>
string(5) "19.98"
["price_old"]=>
...
}
array(6) {
["price"]=>
string(4) "7.99"
["price_old"]=>
...
}
}
Greetings and Thank You!
According to the array definition it is impossible. Any array item must have key and value, documentation for array starts from:
An array in PHP is actually an ordered map. A map is a type that associates values to keys
You will always have numeric keys. As #lubart already said: it's impossible to have an array without keys. Btw., all of the the follwing arrays are completely equal:
$array1 = array([0] => array([0] => 'hi', [1] => array([0] => '23.5')));
$array2 = array(array('hi', array('23.5')));
$array3 = [['hi', ['23.5']]];
$array4 = [ [0] => [ [0] => 'hi', [1] => [ [0] => '23.5' ] ] ];

I am unable to read the only emails in the form of array

I have one array. That array assign to one variable but i am unable to read only emails in that array.That array in given below.
$users = array(3) { [0]=> object(stdClass)#404 (4) { ["guid"]=> string(1) "2" ["name"]=> string(13) "xyz" ["username"]=> string(13) "xyz" ["email"]=> string(23) "xyz#gmail.com" } [1]=> object(stdClass)#405 (4) { ["guid"]=> string(3) "138" ["name"]=> string(12) "wxyz" ["username"]=> string(5) "wxyz" ["email"]=> string(21) "wxyz#gmail.com" } [2]=> object(stdClass)#406 (4) { ["guid"]=> string(3) "126" ["name"]=> string(13) "xxxx" ["username"]=> string(7) "xxxx" ["email"]=> string(17) "xxxx#gmail.com" } }
I need ouput like that
array(3) { [0]=> string(22) "xyz#gmail.com" [1]=> string(19) "wxyz#gmail.com" [3]=> string(19) "xxxx#gmail.com"}
Please give me reply.Advance thank you very much.
You can simply use an array_walk function over here like as
$result = [];
array_walk($users,function($v,$k)use(&$result){
$result[$k] = $v->email;
});
Using array_map
$result = array_map(function($v){return $v->email;},$arr);
You can try preg_grep() to return particular pattern only from an array.
preg_grep( "your Pattern", $array);
Check sample below
$email_only_array = preg_grep("/^[A-z0-9_\-]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z.]{2,4}$/", $your_array);
Example:
// Your array
$array = array("john","wxyz","aaa#mail.com", "wxyz", "bbb#mail.com", "ccc#mail.com");
// validating the value as array
$email_only_array = preg_grep("/^[A-z0-9_\-]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z.]{2,4}$/", $array);
// Output
print_r($email_only_array);
Output
Array ( [2] => aaa#mail.com [4] => bbb#mail.com [5] => ccc#mail.com )
Refer this also, http://php.net/manual/en/function.preg-grep.php

Split Values in Array Using Explode to form Multidimensional Array

I am new to PHP so be kind. :)
I have a 3 deep array. Something like this:
Array(5) {
[0]=> array(5) {
[0]=> string(0) ""
[1]=> string(21) "0,245.19000000,864432"
[2]=> string(21) "1,245.26000000,864432"
[3]=> string(21) "2,245.49000000,864432"
[4]=> string(21) "4,245.33000000,864432"
}
[1]=> array(5) {
[0]=> string(0) ""
[1]=> string(21) "0,245.19000000,864453"
[2]=> string(21) "1,245.26000000,864453"
[3]=> string(21) "2,245.49000000,864453"
[4]=> string(21) "4,245.33000000,864453"
}
}...
I want to explode the inner string by commas ("2,245.49000000,864453") so the arrays becomes 4 deep like so:
Array(5) {
[0]=> array(5) {
[0]=> string(0) ""
[1]=> array (3)
[0]=> "0"
[1]=> "245.19000000"
[2]=> "864432"
[2]=> array (3)
[0]=> "1"
[1]=> "245.26000000"
[2]=> "864432"
[3]=> array (3)
[0]=> "3"
[1]=> "245.49000000"
[2]=> "864432"
[4]=> array (3)
[0]=> "4"
[1]=> "245.3000000"
[2]=> "864432"
[4]=> array (3)
[0]=> "5"
[1]=> "245.3300000"
[2]=> "864432"
}
}
...
So far I have:
$done = array();
for ($i = 0; $i<=count($chunks); $i++) { //loops to get size of each 2d array
$r = count($chunks[$i]);
for ($c = 0; $c<=count($chunks[$r]); $c++) { //loops through 3d array
$arrayparts = $chunks[$i][$c];
$done[] = explode(",", $arrayparts); //$arrayparts is 3d array string that is exploded each time through loop
}
}
I think this code should work but when I var_dump nothing prints?
Can someone help me learn?
Thanks!
Suggested:
$chunks is 3d array
foreach($chunks as $innerArray) {
$result[] = array_map(function($v){
return explode(",", $v);
}, $innerArray);
}
Don't make it complicated, just use this:
(Here I go through each innerArray with a foreach loop and then I go through all values with array_map() and explode it and return it to the results array)
<?php
foreach($arr as $innerArray) {
$result[] = array_map(function($v){
return explode(",", $v);
}, $innerArray);
}
print_r($result);
?>
This uses array_map() two times. Maybe a better way but I'm on beer three:
$result = array_map(function($v){
return array_map(function($v){ return explode(',', $v); }, $v);
}, $array);

How to add key name in nested arrays?

I have the following array:
array(5) {
[0]=> array(3) {
[0]=> string(10) "2013-09-18"
[1]=> string(75) "Ready For Retina HD: Create Pixel-Perfect Assets For Multiple Scale Factors"
[2]=> string(74) "ready-for-retina-hd-create-pixel-perfect-assets-for-multiple-scale-factors"
}
[1]=> array(3) {
[0]=> string(10) "2010-10-20"
[1]=> string(40) "Taking A Closer Look At Tech Conferences"
[2]=> string(40) "taking-a-closer-look-at-tech-conferences"
}
[2]=> array(3) {
[0]=> string(10) "2014-10-19"
[1]=> string(29) "Wayfinding For The Mobile Web"
[2]=> string(29) "wayfinding-for-the-mobile-web"
}
[3]=> array(3) {
[0]=> string(10) "2014-05-15"
[1]=> string(24) "Freebie: Icons Of Autumn"
[2]=> string(23) "freebie-icons-of-autumn"
}
[4]=> &array(1){
[0]=> string(0) ""
}
}
How would I go about assigning key names to each part of the inner array? E,g date, title, pathname.
I understand you can do something like this to create an array with certain keys, but how does this work with multiple nested arrays? And how can it be assigned after array creation?
$keys = array('Date', 'Title', 'Filepath');
Assuming $array1 is your main array (with 5 values).
foreach($array1 as $a)
{
if (len($a) == 3)
$array2[] = array("Date" => $a[0], "Title" => $a[1], "Filepath" => $a[2]);
}
$array1 = $array2;
Use a foreach.
$new = [];
foreach ($origArray as $inner) {
$new[] = [
"date" => $inner[0],
"title" => $inner[1],
"filepath" => $inner[2]
];
}
$origArray = $new;
This doesn't handle cases where the item does not conform to the "standard" (e.g item 4) but this should get you started.

sort the array and remove part of it afterwards

I have a 2d array called $myarray and I use var_dump($myarray), it gives me the following:
array(4) {
[0]=> array(3) {
[0]=> string(11) "PAY000003RV"
[1]=> string(3) "EUR"
[2] => string(9) "43,543.23"
}
[1]=> array(3) {
[0]=> string(11) "PAY000002PE"
[1]=> string (3) "USD"
[2]=> string(9) "13,432.34"
} [2]=> array(3) {
[0]=> string(11) "PAY000001YB"
[1] => string(3) "GBP"
[2]=> string(8) "3,432.21"
} [3]=> array(3) {
[0]=> string(11) "PAY000004TS"
[1]=> string(3) "CAD"
[2]=> string(8) "2,321.34"
}
}
I want to get the following output:
GBP 3,432.21
USD 13,432.34
EUR 43,543.23
CAD 2,321.34
so I try to use substr($myarray[0][0], 8, 1), substr($myarray[1][0], 8, 1), substr($myarray[2][0], 8, 1), substr($myarray[3][0], 8, 1) to get the value 3,2,1,4 in order to use it to sort the array to the above order and then delete $myarray[0][0], $myarray[1][0], $myarray[2][0], $myarray[3][0] which are the "PAY0000.." elements in every row, but I am not sure how exactly to implement that, any experts could help me with that? any help will be greatly appreciated!
//Extract sort key
$tmp=array();
foreach($myarray as $m) $tmp[$m[0]]=array($m[1],$m[2]);
//Sort array
ksort($tmp);
//Create output
foreach($tmp as $m) echo $m[0].' '.$m[1];
Some comments:
You can sort by PAY00000nXY without extracting n
The code assumes you need the array for more than printing it out, else it might be inefficient
Let's say your array is assigned to variable $foo
$values = array();
foreach ( $foo as $bar ) {
foreach ( $bar as $val ) {
$values[] = $val[1] . ' ' . $val[2];
}
}
Then you will have the array $values with the values you need.

Categories