How can I map two arrays based on specific indexes? - php

Array1 ( [0] => [1] => [2] => 3 [3] => [4] => 5 [5] => [6] => )
Array2 ( [0] => URD [1] => ISL )
I want to map $array2 values to $array1 indexes (those having values 3 and 5) and I want get an array like this:
Array ( [0] => [1] => [2] => URD [3] => [4] => ISL [5] => [6] => )
I have tried the following:
$newArray = array_values(array_filter(array_merge($array1,$array2)));
but the actual result is:
Array([0] => 3[1] => 5[2] => URD[3] => ISL)
The expected result should be:
Array ( [0] => [1] => [2] => URD [3] => [4] => ISL [5] => [6] => )

Code
Try the following:
<?php
$array1 = ["", "", "3", "", "5", "", ""];
$array2 = ["URD", "ISL"];
foreach($array1 as $id => $a1){
//for each item in array 1
if($a1){
//if the array 1 item has a value
$array1[$id] = array_shift($array2);
//replace it with an item from array 2
}
if(empty($array2)){
//if there are no more values left to share in array 2, stop
break;
}
}
var_dump($array1);
Output
array(7) {
[0]=>
string(0) ""
[1]=>
string(0) ""
[2]=>
string(3) "URD"
[3]=>
string(0) ""
[4]=>
string(3) "ISL"
[5]=>
string(0) ""
[6]=>
string(0) ""
}
Caveats
The method assumes that there will be values in both array 1 and array 2.
Once the values in array 2 have been split out and array 2 is empty, array 1 items with set values will no longer be affected.
The method does not care what the value set in array 1 is, just that there is a value.
Further reading
foreach()
array_shift()
Codepen
https://3v4l.org/RDQY6

This solution works and simple to understands as OPS requested...
<?
$array1 = ["", "", "3", "", "5", "", ""];
$array2 = ["URD", "ISL"];
$i =0;
foreach($array1 as $keys=>$values) {
if($values == 3 || $values ==5) {
if(isset($array2[$i])){
$array1[$keys] = $array2[$i];
$i++;
}else { break; }
}
}
print_R($array1);
?>
it will replace the array2 values from array 1 values wherever 5 & 3 will come and which is independent of their sorting order.
example
$array1 = ["5", "", "3", "", "", "", ""]; will be converted into
$array1 = ["URD", "" ,"ISL","","",""];
if you want it in order like 3 should always come first then first sort array1 then use my code...
if you want 3 should be replace by URD and 5 should be replace by ISL
then you if codition will be different

Just another way to do it... (untested, but it should work)
<?php
$a = array ( 0 => '', 1 => '', 2 => 3, 3 => '', 4 => 5, 5 => '', 6 => '' );
$b = array ( 0 => 'URD', 1 => 'ISL' );
$c = array_replace ( $a, array_combine ( array_keys ( array_filter ( $a ) ), $b ) );
print_r ( $c );
?>

Related

PHP Find same values in TWO multidimensional arrays and map them in separate array

I have two multidimensional arrays:
Array (
[1] => Array
(
[id] => 1
[email] => aaa#mail.com
some irrelevant pairs
)
[2] => Array
(
[id] => 2
[email] => bbb#mail.com
some irrelevant pairs
)
[3] => Array
(
[id] => 3
[email] => ccc#mail.com
some irrelevant pairs
))
Array (
[1] => Array
(
[id] => 4
[email] => aaa#mail.com
some irrelevant pairs
)
[2] => Array
(
[id] => 5
[email] => bbb#mail.com
some irrelevant pairs
)
[3] => Array
(
[id] => 6
[email] => ccc#mail.com
some irrelevant pairs
))
As you see they both have key 'email' with the same values. How to extract the pairs of IDs as key-value pairs in the separate array as a map of the same emails ? I tried with foreach loops and in_array function, but something was wrong. This is what I need:
Result (pairs of IDs where e-mail values are the same:
my_array_with_pairs_of_IDs = ( "1" => "4", "2" => "5", "3" => "6" );
Please help, Thanks a lot!
Performance optimized, based on #Andreas answer:
$map1 = array_column($arr1, 'id', 'email');
$map2 = array_column($arr2, 'id', 'email');
$result = [];
foreach ($map1 as $email => $id)
{
if (isset($map2[$email]))
{
$result[$id] = $map2[$email];
}
}
removed $arr1 and $arr2 overriding;
added $result declaration.
You can use array_column to make two flat arrays that you can use array_search in.
If array_search returns not false, it's the key of the found match.
$arr1 = array_column($arr1, 'email', 'id');
$arr2 = array_column($arr2, 'email', 'id');
foreach($arr1 as $key => $val){
$find = array_search($val, $arr2);
if($find !==false) $result[$key] = $find;
}
var_dump($result);
Output:
array(3) {
["1 "]=>
string(2) "4 "
["2 "]=>
string(2) "5 "
["3 "]=>
string(2) "6 "
}
https://3v4l.org/6XhUd
You can use this method and store data in new array
$result = [];
foreach($a1 as $a){
foreach($b1 as $b){
if($b[email] == $a[email])
$result[] = [$a[id]=>$b[id]];
}
}

How to count repeated values from an array or json in php

I would like to know how to tell the value of an array or json. Example: I want to count the value of the item GRUPO_OK = SIM and MRS_central = 1001.
Output:
MRS_central: "1001" => 2
GRUPO_OK: "SIM" => 3
Example array
Array ( [data] => Array ( [0] => Array ( [MRS_central] => 1003 [MRS_ipsat] => [GRUPO_OK] => NÃO ) [1] => Array ( [MRS_central] => 1001 [MRS_ipsat] => [GRUPO_OK] => SIM ) [2] => Array ( [MRS_central] => 1001 [MRS_ipsat] => [GRUPO_OK] => SIM ) [3] => Array ( [MRS_central] => 1002 [MRS_ipsat] => 10.4.0.253 [GRUPO_OK] => SIM ) ) )
Example json
{
data: [
{
MRS_central: "1001",
MRS_ipsat: "",
GRUPO_OK: "SIM"
},
{
MRS_central: "1001",
MRS_ipsat: "",
GRUPO_OK: "SIM"
},
{
MRS_central: "1003",
MRS_ipsat: "",
GRUPO_OK: "SIM"
},
{
MRS_central: "1002",
MRS_ipsat: "10.4.0.253",
GRUPO_OK: "NÃO"
}
]
}
If you have array_column(), you can extract each column. Then, you can use array_count_values() to count how many times a value appears in an array.
$mrs_grupo = array_column($arr['data'], 'GRUPO_OK');
$count = array_count_values($mrs_grupo);
print_r($count);
//RESULT
array(2) {
["SIM"]=>
int(3)
["NÃO"]=>
int(1)
}

How set the array in php?

I have got this Array
Array ( [0] => 9314802498 [1] => 9314801890 [2] => MOSWAPELE ESTHER [3] => BENNETH )
I Want to retrieve like that Array
Array ( [0] => 9314802498 [1] => MOSWAPELE ESTHER [2] => 9314801890 [3] => BENNETH )
This can help -
$array = array ( 0 => 9314802498, 1 => 9314801890, 2 => 'MOSWAPELE ESTHER', 3 => 'BENNETH' );
$temp= array_chunk($array, count($array)/2);
$final = array();
foreach($temp[0] as $key => $val) {
$final[]= $val;
$final[]= !empty($temp[1][$key]) ? $temp[1][$key] : null;
}
var_dump($final);
Output
array(4) {
[0]=>
float(9314802498)
[1]=>
string(16) "MOSWAPELE ESTHER"
[2]=>
float(9314801890)
[3]=>
string(7) "BENNETH"
}
Assuming the count of numbers and names would be equal in that array. If not -
$temp= array_chunk($array, ceil(count($array)/2));
change the key
$arr = Array ( [0] => 9314802498 [1] => 9314801890 [2] => MOSWAPELE ESTHER [3] => BENNETH );
$arr[1] = 'MOSWAPELE ESTHER';
$arr[2] = '9314801890';
It will give you desired answer
Try replacing the key values like this:
$arr1 = array('9314802498', '9314801890', 'MOSWAPELE ESTHER', 'BENNETH');
$temp = $arr1[1];
$arr1[1] = $arr1[2];
$arr1[2] = $temp;
Try this code.
$arr = array(
0 => 9314802498,
1 => 9314801890,
2 => 'MOSWAPELE ESTHER',
3 => 'BENNETH'
);
$temp_val = $arr[1];
$arr[1] = $arr[2];
$arr[2] = $temp_val;
print_r($arr);
Output
Array ( [0] => 9314802498 [1] => MOSWAPELE ESTHER [2] => 9314801890 [3] => BENNETH )

Enhancing asort by order of keys

I am using asort to sort the numeric array. For e.g.
$arr = [0,1,1,2,1,2,2,3];
After running asort I am getting:
Array
(
[0] => 0
[4] => 1
[2] => 1
[1] => 1
[6] => 2
[3] => 2
[5] => 2
[7] => 3
)
But I am expecting to get it in this order:
Array
(
[0] => 0
[1] => 1
[2] => 1
[4] => 1
[3] => 2
[5] => 2
[6] => 2
[7] => 3
)
See the difference in order of the keys above.
First sort the array.
Then generate an array by flipping in a way so that the keys can be separated according to values. Sort the arrays with keys and merge them to an array. And the combine the keys with the sorted values.
$arr = [0,1,1,2,1,2,2,3];
asort($arr);
$sorted = $arr;
$flipped = $new_keys = array();
foreach($arr as $key => $val) {
$flipped[$val][] = $key; // Get the keys
}
foreach($flipped as $key => $val_array) {
asort($val_array); // Sort the keys
$new_keys = array_merge($new_keys, $val_array);
}
$final = array_combine($new_keys, $sorted); // Combine them again
var_dump($final);
Output
array(8) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(1)
[4]=>
int(1)
[3]=>
int(2)
[5]=>
int(2)
[6]=>
int(2)
[7]=>
int(3)
}
This should work for you:
First walk through each array value with array_walk() and change each value to an array containing the value and the key.
After this use uasort() to sort your array and if both values are the same you use the key to choose which one should be first.
At the end just use array_column() to transform your array back.
<?php
$arr = [0,1,1,2,1,2,2,3];
array_walk($arr, function(&$v, $k){
$v = ["value" => $v, "key" => $k];
});
uasort($arr, function($a, $b){
if($a["value"] == $b["value"]) {
if($a["key"] == $b["key"])
return 0;
return $a["key"] > $b["key"] ? 1 : -1;
}
return $a["value"] > $b["value"] ? 1 : -1;
});
$arr = array_column($arr, "value", "key");
print_r($arr);
?>
output:
Array
(
[0] => 0
[1] => 1
[2] => 1
[4] => 1
[3] => 2
[5] => 2
[6] => 2
[7] => 3
)

how to get value from associative array

This is my array :
Array
(
[0] => Array
(
[0] => S No.
[1] => Contact Message
[2] => Name
[3] => Contact Number
[4] => Email ID
)
[1] => Array
(
[0] => 1
[1] => I am interested in your property. Please get in touch with me.
[2] => lopa <br/>(Individual)
[3] => 1234567890
[4] => loperea.ray#Gmail.com
)
[2] => Array
(
[0] => 2
[1] => This user is looking for 3 BHK Multistorey Apartment for Sale in Sohna, Gurgaon and has viewed your contact details.
[2] => shiva <br/>(Individual)
[3] => 2135467890
[4] => sauron82#yahoo.co.in
)
)
How can I retrieve all data element wise?
You can get information about arrays in PHP on the official PHP doc page
You can access arrays using square braces surrounding the key you like to select [key].
So $array[1] will give yoo:
Array
(
[0] => 1
[1] => I am interested in your property. Please get in touch with me.
[2] => lopa <br/>(Individual)
[3] => 1234567890
[4] => loperea.ray#Gmail.com
)
And $array[1][2] will give you:
lopa <br/>(Individual)
Or you can walkt through the elements of an array using loops like the foreach or the for loop.
// perfect for assoc arrays
foreach($array as $key => $element) {
var_dump($key, $element);
}
// alternative for arrays with seamless numeric keys
$elementsCount = count($array);
for($i = 0; $i < $elementsCount; ++$i) {
var_dump($array[$i]);
}
You have integer indexed elements in multidimensional array. To access single element from array, use array name and it's index $myArray[1]. To get inner element of that previous selected array, use second set of [index] - $myArray[1][5] and so on.
To dynamically get all elements from array, use nested foreach loop:
foreach ($myArray as $key => $values) {
foreach ($values as $innerKey => $value) {
echo $value;
// OR
echo $myArray[$key][$innerKey];
}
}
The solution is to use array_reduce:
$header = array_map(
function() { return []; },
array_flip( array_shift( $array ) )
); // headers
array_reduce( $array , function ($carry, $item) {
$i = 0;
foreach( $carry as $k => $v ) {
$carry[$k][] = $item[$i++];
}
return $carry;
}, $header );
First of all we get the header from the very first element of input array. Then we map-reduce the input.
That gives:
$array = [['A', 'B', 'C'], ['a1', 'b1', 'c1'], ['a2', 'b2', 'c2'], ['a3', 'b3', 'c3']];
/*
array(3) {
'A' =>
array(3) {
[0] =>
string(2) "a1"
[1] =>
string(2) "a2"
[2] =>
string(2) "a3"
}
'B' =>
array(3) {
[0] =>
string(2) "b1"
[1] =>
string(2) "b2"
[2] =>
string(2) "b3"
}
'C' =>
array(3) {
[0] =>
string(2) "c1"
[1] =>
string(2) "c2"
[2] =>
string(2) "c3"
}
}
*/
I think this is what you are looking for
$array = Array
(
0=> Array
(
0 => 'S No.',
1 => 'Contact Message',
2 => 'Name',
3 => 'Contact Number',
4 => 'Email ID'
),
1 => Array
(
0 => 1,
1 => 'I am interested in your property. Please get in touch with me.',
2 => 'lopa <br/>(Individual)',
3 => '1234567890',
4 => 'loperea.ray#Gmail.com',
),
2 => Array
(
0 => 2,
1 => 'This user is looking for 3 BHK Multistorey Apartment for Sale in Sohna, Gurgaon and has viewed your contact details.',
2 => 'shiva <br/>(Individual)',
3 => '2135467890',
4 => 'sauron82#yahoo.co.in',
)
);
$result_array = array();
array_shift($array);
reset($array);
foreach($array as $x=>$array2){
foreach($array2 as $i => $arr){
if($i == 1){
$result_array[$x]['Contact Message'] = $arr;
}elseif($i == 2){
$result_array[$x]['Name'] = $arr;
}elseif($i == 3){
$result_array[$x]['Contact Number'] =$arr;
}elseif($i == 4){
$result_array[$x]['Email ID'] = $arr;
}
}
}
print_r($result_array);

Categories