make an Array from 2 Arrays - php

I have this:
$Array1 = "FirstName, LastName, Email";
$Array2 = "John, Doe, johndoe#email.com";
Using a foreach or other means, Could the final array format to look like this?
$mergedArrays = array(
'FirstName' =>"John",
'LastName' => "Doe",
'Email' =>'johndoe#email.com',
);
print_r($mergedArrays);

If you are sure that both array will contain the same number separeted by comma, use this:
Version 1 (testing with 100000 takes ~0.08s, +-4x faster)
<?php
$Array1 = "FirstName, LastName, Email";
$Array2 = "John, Doe, johndoe#email.com";
$Array1 = explode(',', preg_replace('/\s*,\s*/',',',$Array1)); //remove spaces before and after comma
$Array2 = explode(',', preg_replace('/\s*,\s*/',',',$Array2));
if(count($Array1) == count($Array2)) {
$result = array_combine($Array1, $Array2);
}
print_r($result);
Output:
Array (
[FirstName] => John
[LastName] => Doe
[Email] => johndoe#email.com
)
Alternative version from #castis (testing with 100000 takes ~0.3s)
$Array1 = explode(',',$Array1);
$Array2 = explode(',',$Array2);
$result = array_combine(array_map('trim', $Array1), array_map('trim', $Array2));

If you must use a foreach (where array_combine would do):
<?php
$fields = ['FirstName', 'LastName', 'Email'];
$values = ['John', 'Doe', 'johndoe#email.com'];
foreach($fields as $k => $field)
$result[$field] = $values[$k];
var_export($result);
Output:
array (
'FirstName' => 'John',
'LastName' => 'Doe',
'Email' => 'johndoe#email.com',
)

Related

Keys and Values re-formatting in PHP

Please read the whole question before attempting to answer. If I have two associative arrays where some values match just once:
$array1 = ['key1' => 'value1', 'key3' => 'value2', etc...];
$array2 = ['key2' => 'value1', 'key4' => 'value2', etc...];
but $array2 is longer than $array 1, and in those cases the keys don't have values:
$array1 = ['key1' => 'value1', 'key3' => 'value2'];
$array2 = ['key2' => 'value1', 'key4' => 'value2', 'key5' => 'value3'];
Then how can I combine them to get the following result:
$array3 = [
'value1' => [$myconstant => key2],
'value2' => [$myconstant => key4],
'value3' => [$myconstant => ''],
etc...];
Notice that in cases where there is no match, an empty string is used instead of the key in the embedded associative array. In fact, the only reason why $array1 is necessary is because I need to know when there is a match with $array2 to get the correct format.
The values will not repeat themselves along the etc... chain.
I'm using Laravel and am trying to use Collections, but basic PHP solutions are okay too. Thank you very much.
I guess the biggest hurdle you have is how to transform those values in keys and keys into values. array_flip is the answer to that problem. Once you have that, you can solve your problem with a simple foreach loop.
$myconstant = 'foo';
$array1 = ['key1' => 'value1', 'key3' => 'value2'];
$array2 = ['key2' => 'value1', 'key4' => 'value2', 'key5' => 'value3'];
// array_flip switches keys and values in an array
$flip1 = array_flip($array1);
$flip2 = array_flip($array2);
$array3 = [];
foreach($flip2 as $key => $value) {
if(!isset($flip1[$key])) {
$array3[ $key ] = [ $myconstant => '' ];
} else {
$array3[ $key ] = [ $myconstant => $value ];
}
}
Laravel Collections have a flip() method, too. That might help you translating the script into Laravel.
<?php
$array1 = ['key1' => 'value1', 'key3' => 'value2'];
$array2 = ['key2' => 'value1', 'key4' => 'value2', 'key5' => 'value3'];
function x (array $a= array(), array $b = array()) {
$array = array();
$index = new ArrayObject($a);
$seed = new ArrayObject($b);
$a_it = $index->getIterator();
$b_it = $seed->getIterator();
while ($a_it->valid()) {
$x = $a_it->current();
$y = ($b_it->valid()) ? $b_it->current() : NULL;
if ($y !== NULL) {
# there is a value to compare against
if ($x === $y) {
$array["{$x}"] = array('myConst'=>$a_it->key());
}
$b_it->next();
} else {
# there is no value to compare against
$array["{$x}"] = array('myConst'=> '');
}
$a_it->next();
}
return $array;
}
$read = x($array2, $array1);
print_r($read);

PHP - How to check two arrays and search for matching keys and merge the values

How to check two arrays and search for matching keys and merge the values of the 1st array with the matching keys of the second array.Please help me as I'm new to this.
example :
1st array = {id => 11,name => 'name',age => 18 }
2nd array = {id,name,age,school}
I want to get the result by adding the matching values to the 2nd array
2nd array = {id => 11,name => 'name',age => 18,school => }
try this
$a = ['id' => 11,'name' => 'name','age' => 18];
$b = array_flip(['id','name','age','school']);
foreach($b as $key => &$value){
$value = '';
}
$result = array_merge($b, $a);
One of the simple way is looping
$first= array('id' => 11,'name' => 'name','age' => 18 );
$second = array('id','name','age','school');
foreach ($second as $value) {
if(isset($first[$value])){
$final[$value] = $first[$value];
}
};
print_r($final);
Second Array flip and array merge
$first = ['id' => 11,'name' => 'name','age' => 18];
$second= array_flip(['id','name','age','school']);
foreach($second as $key => s$value){
$value = '';
}
$result = array_merge($second, $first);
print_r($result);
Use array_merge
<?php
$array1 = array('id' => '11', 'name' => 'name', 'age' => 18);
$array2 = array('id','name','age','school');
$array3 = array_merge(array_fill_keys($array2, null), $array1);
print_r($array3);
?>

PHP combine multiple array into one with key

I am lost actually, not sure how to explain the question.
Suppose I have three array
$name = array('mark', 'jones', 'alex');
$age = array(12, 23, 34);
$country = array('USA', 'UK', 'Canada');
What I am looking for is:
array(
0 => array(
'name' => 'mark',
'age' => 12,
'country' => 'USA'
)
1 => array(
'name' => 'jones',
'age' => 23,
'country' => 'UK'
)
2 => array(
'name' => 'alex',
'age' => 34,
'country' => 'Canada'
);
Couldn't figure out any built in PHP array function to handle it.
try something like this
$result = array();
foreach($name as $key => $value)
{
$result[$key] = array (
'name' => $value,
'age' => $age[$key],
'country' => $country[$key]
);
}
echo '<pre>';
print_r($result);
?>
You could do it without any manual looping like this:
// array_map with null callback merges corresponding items from each input
$merged = array_map(null, $name, $age, $country);
// walk over the results to change array_map's numeric keys to strings
$keys = ['name', 'age', 'country'];
array_walk(
$merged,
function(&$row) { $row = array_combine(['name', 'age', 'country'], $row); }
);
print_r($merged);
You can even write it in such a way that the keys in the result are equal to the names of the variables $name, $age, $country without needing to repeat yourself:
// Here "name", "age" and "country" appear only once:
$inputs = compact('name', 'age', 'country');
$merged = call_user_func_array('array_map', [null] + $inputs);
$keys = array_keys($inputs);
array_walk(
$merged,
function(&$row) use($keys) { $row = array_combine($keys, $row); }
);
However, to be frank it might be more readable (and it might even be faster) to just for over the inputs (assuming they have the same number of items) and do it manually.

Fill an array in php with two array

I have two numeric arrays (these arrays will always have the same number of keys and values).
$array1 = array(0 => "key1", 1 => "key2");
$array2 = array(0 => "value1", 1 => "value2");
$array_final = array(value of the $array1 => $value of the array2);
If I write a while and fill the $array_final, it only fills with the last key and value
So it's like:
for ($i = 0; $i < count($array(1))
{
$array_final = array($array1[$i] => $array2[$i]);
}
$array_final = array("key2" => "value2");
But I want:
$array_final = array("key1" => "value1", "key2" => "value2");
You want array_combine
It does exatcly what you need
So basically
$array1 = array(0 => "key1", 1 => "key2");
$array2 = array(0 => "value1", 1 => "value2");
$array_final = array_combine($array1, $array2);
for ($i=0; $i< sizeof($array1) && $i< sizeof($array2) ; $i++)
{
$array_final[$array1[$i]] =$array2[$i];
}
You may try below code.
$array1 = array(0 => "key1", 1 => "key2");
$array2 = array(0 => "value1", 1 => "value2");
$array_final = combine_if_same_keys($array1,$array2);
print_r($array_final);
function combine_if_same_keys( $array_one, $array_two ) {
$expected = false;
ksort($array_one);
ksort($array_two);
$diff = array_diff_key($array_one, $array_two);
if( empty($diff) && count($array_one) == count($array_two) ) {
$expected = array_combine( $array_one, $array_two );
}
return $expected;
}

php array merge and convert to json

I have two arrays (below). Is it possible to convert them into json string?
Array
(
[0] => size
[1] => color
)
Array
(
[0] => L
[1] => Black
)
Output structure should be:
[
{"name":"size","value":"L"},
{"name":"color","value":"Black"}
]
Thanks!
Sure:
$array1 = array('size', 'color');
$array2 = array('L', 'Black');
$jsonArray = array();
foreach (array_combine( $array1, $array2 ) as $name => $value) {
$jsonArray[] = array('name' => $name, 'value' => $value);
}
echo $json = json_encode($jsonArray);
This gives you
[{"name":"size","value":"L"},{"name":"color","value":"Black"}]
this here should work:
$json = json_encode( array_combine( $array1, $array2 ) );
Something like this should work just how you want:
<?php
$keys = array("size", "color");
$values = array("L", "Black");
$array = array();
foreach ($keys as $i => $key) {
$array[] = array(
"name" => $key,
"value" => $values[$i]
);
}
$json = json_encode($array);
var_dump($json);
//string(62) "[{"name":"size","value":"L"},{"name":"color","value":"Black"}]"
?>
$array1 = array('size', 'color');
$array2 = array('L', 'Black');
$result = array_combine($array1 , $array2);
$json = array();
foreach($result as $key => $val){
$json[] = array('name' => $key, 'value' => $value);
}
$json = json_encode($json);
I think you are looking for this:
$array1 = array('size', 'color');
$array2 = array('L', 'Black');
for($i=0;$i<sizeof($array1);$i++)
{
$array3[]=array($array1[$i]=>$array2[$i]);
}
echo json_encode($array3);
?>
Output:
[{"size":"L"},{"color":"Black"}]

Categories