Merge two arrays with the same key but in different depth? - php

$arr = array('one' => array('one_1' => array('one_2' => '12')), 'two', 'three');
$arr2 = array('one_2' => 'twelve');
$merge = array_merge($arr, $arr2);
print '<pre>';
var_dump($merge);
print '</pre>';
gives:
array(4) {
["one"]=>
array(1) {
["one_1"]=>
array(1) {
["one_2"]=>
string(2) "12"
}
}
[0]=>
string(3) "two"
[1]=>
string(5) "three"
["one_2"]=>
string(6) "twelve"
}
I want the value of key one_2 in the first array to be replaced with the value of the same key in the second array. So the result would be:
array(4) {
["one"]=>
array(1) {
["one_1"]=>
array(1) {
["one_2"]=>
string(2) "twelve"
}
}
[0]=>
string(3) "two"
[1]=>
string(5) "three"
}

array_walk_recursive($arr, function (&$value, $key, $replacements) {
if (isset($replacements[$key])) {
$value = $replacements[$key];
}
}, $arr2);
Note that this uses PHP 5.3+ syntax.

Related

Extract elements of certain type from an array in PHP

I have a multidimensional array I obtained from an Excel file (raw data from cells stripped of any formatting, styling info,etc.). Example of array:
array(1) {
[0]=>
array(4) {
[1]=>
array(1) {
["A"]=>
string(5) "aaaaa"
}
[2]=>
array(1) {
["A"]=>
NULL
}
[3]=>
array(1) {
["A"]=>
NULL
}
[4]=>
array(1) {
["A"]=>
float(666)
}
}
}
String-type cells represent ordinary text entered into a worksheet cells, while float-type cells represent numbers entered there.
Is there any method to extract the 'strings' and 'floats' from such an array? Or, can one at least delete all/filter out other info from an array by the type of its elements, leaving only 'string' and 'float' elements there?
Thank you!
Just check the array items recursively and remove the items which is not string, float or array with data.
Code example:
<?php
$data = [
[
['A' => 'aaaaa'],
['A' => null],
['A' => null],
['A' => (float)666]
]
];
function filterData($array)
{
foreach ($array as $key => &$value) {
if (is_array($value))
$value = filterData($value);
if ($value === [] || (!is_array($value) && !is_string($value) && !is_float($value)))
unset($array[$key]);
}
return $array;
}
var_dump(filterData($data));
/* result
array(1) {
[0]=>
array(2) {
[0]=>
array(1) {
["A"]=>
string(5) "aaaaa"
}
[3]=>
array(1) {
["A"]=>
float(666)
}
}
}
*/
As an alternative you might use a combination of array_map and array_filter and in the callback of array_filter check if the value is either a float or a string:
$arrays = [
[
['A' => 'aaaaa'],
['A' => null],
['A' => null],
['A' => (float)666]
]
];
$arrays = array_map(function($x) {
return array_filter($x, function($y) {
return is_float($y['A']) || is_string($y['A']);
});
}, $arrays);
var_dump($arrays);
Demo
That would result in:
array(1) {
[0]=>
array(2) {
[0]=>
array(1) {
["A"]=>
string(5) "aaaaa"
}
[3]=>
array(1) {
["A"]=>
float(666)
}
}
}

Combining arrays - PHP

I have an array like:
print_r($arr);
array(2) {
["'type'"]=>
array(3) {
[0]=>
string(17) "tell" // <----
[1]=>
string(6) "mobile" // <----
[2]=>
string(6) "address" // <----
}
["'value'"]=>
array(3) {
[0]=>
string(11) "+00.0000000" // tell
[1]=>
string(11) "12345678" // mobile
[2]=>
string(11) "Blah SQ." // address
}
}
I want a final string like:
tell = +00.0000000<br />mobile = 12345678<br />address = Blah SQ.
Now it's been more than an hour I'm struggling with this but no results yet, anyone could help me with this? I would appreciate anykind of help.
Thanks
=======================================
What I have tried:
$arr is an array so I did:
foreach($arr as $values){
// here also $values is an array, so I needed another foreach to access to items:
$i = 0;
foreach($values as $items){
// now making the final output
#$output.= $items['type'][$i] . '=' . $items['value'][$i] . '<br />';
$i++;
}
}
I'd go for array_combine(). Basically it does what you request:
$yourArray = [
"type" => ["tell", "mobile", "address"],
"value" => ["+00.0000000", "12345678", "Blah SQ."]
];
$combined = array_combine($yourArray["type"], $yourArray["value"]);
will be
$combined = [
"tell" =>"+00.0000000",
"mobile" =>"12345678",
"address" =>"Blah SQ."
];
Lastly, you can iterate through that array and then join the values:
$finalArray=array();
foreach($combined as $type=>$value)
$finalArray[]="$type=$value";
$string = join("<br/>", $finalArray); // Will output tell=+00.000000<br/>mobile=12345678<br/>address=Blah SQ.
It's not the fastest method but you'll learn quite a bit about arrays.
EDIT (using array_combine by #Dencker)
foreach($arr as $values) {
// here also $values is an array, so I needed another foreach to access to items:
$v = array_combine($values["'type'"], $values["'value'"]);
foreach($v as $key => $val) {
// now making the final output
$output.= $key . '=' . $val . '<br />';
}
}
Try this
$arr = array(
array(
"'type'" => array('tell', 'mobile', 'address'),
"'value'" => array('+00000', '123123', 'foo')
),
array(
"'type'" => array('tell', 'mobile', 'address'),
"'value'" => array('+10000', '123123', 'bar')
),
array(
"'type'" => array('tell', 'mobile', 'address'),
"'value'" => array('+20000', '123123', 'foobar')
),
);
var_dump($arr);
$output = '';
foreach($arr as $values) {
// here also $values is an array, so I needed another foreach to access to items:
$i = 0;
foreach($values as $items) {
// now making the final output
$output.= $values["'type'"][$i] . '=' . $values["'value'"][$i] . '<br />';
$i++;
}
}
echo $output;
You were referencing the other array in the second loop.
=============================================================
EDIT:
var_dump($arr);
array(3) {
[0]=> array(2) {
["type"]=> array(3) {
[0]=> string(4) "tell"
[1]=> string(6) "mobile"
[2]=> string(7) "address"
}
["value"]=> array(3) {
[0]=> string(6) "+00000"
[1]=> string(6) "123123"
[2]=> string(3) "foo"
}
}
[1]=> array(2) {
["type"]=> array(3) {
[0]=> string(4) "tell"
[1]=> string(6) "mobile"
[2]=> string(7) "address"
}
["value"]=> array(3) {
[0]=> string(6) "+10000"
[1]=> string(6) "123123"
[2]=> string(3) "bar"
}
}
[2]=> array(2) {
["type"]=> array(3) {
[0]=> string(4) "tell"
[1]=> string(6) "mobile"
[2]=> string(7) "address"
}
["value"]=> array(3) {
[0]=> string(6) "+20000"
[1]=> string(6) "123123"
[2]=> string(6) "foobar"
}
}
}
OUTPUT:
tell=+00000
mobile=123123
tell=+10000
mobile=123123
tell=+20000
mobile=123123

How to flatten array in 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
)

Add explode array as keys to new array

$input = "hello|world|look|at|this";
$explode = explode("|", $input);
$array = array("Title" => "Hello!", "content" => $explode);
This will output:
array(2) {
["Title"]=>
string(6) "Hello!"
["content"]=>
array(5) {
[0]=>
string(5) "hello"
[1]=>
string(5) "world"
[2]=>
string(4) "look"
[3]=>
string(2) "at"
[4]=>
string(4) "this"
}
}
But I want them to be keys with a NULL as value as I add values in a later step.
Any idea how to get the explode() function to return as keys? Is there a function from php available?
array_fill_keys can populate keys based on an array:
array_fill_keys ($explode, null);
Use a foreach loop on the explode to add them:
foreach($explode as $key) {
$array["content"][$key] = "NULL";
}
how about array_flip($explode)? That should give you this
array(2) {
["Title"]=>
string(6) "Hello!"
["content"]=>
array(5) {
[hello]=> 1
No nullvalues but atleast you got the keys right
$input = "hello|world|look|at|this";
$explode = explode('|', $input);
$nulls = array();
foreach($explode as $x){ $nulls[] = null; };
$array = array("Title" => "Hello!", "content" => array_combine($explode, $nulls));

How can I make an existing array into a two-dimensional array in PHP?

$i=0;
$array=array("one","two");
foreach($array as &$point)
{
$point[$i]=array($point[$i], $i);
$i++;
}
var_dump($array);
yields:
array(2) { [0]=> string(3) "Ane" [1]=> &string(3) "tAo" }
I was expecting something more like:
[0]=> [0]=> "one" [1]= 1
[1]=> [0]=> "two" [1]= 2
Am I doing the inner block of the foreach wrong, or is there another method I should be using to go from a single to a 2D array?
You mean like this:
$i=1;
$array=array("one","two");
foreach($array as $j => $point)
{
$array[$j]=array($point, $i);
$i++;
}
var_dump($array);
Outputs:
array(2) {
[0]=>
array(2) {
[0]=>
string(3) "one"
[1]=>
int(1)
}
[1]=>
array(2) {
[0]=>
string(3) "two"
[1]=>
int(2)
}
}
$array = array("one","two");
foreach($array as $i => &$point)
{
$point = array($point, $i + 1);
}
var_dump($array);
There were several errors in your code:
You should assign to $point
You should access $point, not $point[$i]
If you had error output turned on (or of you look at the error logs) you'd see Array to string conversion error for your code.
You may use this to define a two dimensional array in PHP
$array = array(
array(0, 1, 2),
array(3, 4, 5),
);

Categories