PHP: Merging arrays - php

Array 1:
Array (
'127.0.0.1',
'235.107.12.3'
)
Array 2:
Array (
'34.235.54.6',
'230.56.78.1'
)
Final Array should like below:
Array (
[127.0.0.1] => Array (
'34.235.54.6',
'230.56.78.1'
),
[235.107.12.3]' => Array (
'34.235.54.6',
'230.56.78.1'
)
)
Please give an advice as to how I can merge these two arrays (array 1 and array 2) to achieve the desired result.

Use array_fill_keys:
$final = array_fill_keys( $array1, $array2 );

Try this one
$a = array_fill_keys($array1, $array2);
Print_r($a);
Output:
Array(
[127.0.0.1]=>
array
(
'34.235.54.6',
'230.56.78.1'
),
[235.107.12.3]'=>
array
(
'34.235.54.6',
'230.56.78.1'
)
)

you can get your job done using loop, for eg. foreach loop here
foreach($array1 AS $val1)
{
foreach($array2 AS $val2)
{
$newarr[$val1][] = $val2;
}
}
print_r($newarr);

<?php
$final = array();
foreach($array1 as $k => $v)
$final[$k] = $array2;
var_dump($final);
?>

$arrayA = array('127.0.0.1','235.107.12.3' );
$arrayB = array('34.235.54.6','230.56.78.1');
$i = 0;
foreach($arrayA as $a){
$arrayC[$i] = arrayB;
$i++;
}

Related

Convert a one dimensional array to two dimensional array

I have an array, whose structure is basically like this:
array('id,"1"', 'name,"abcd"', 'age,"30"')
I want to convert it into a two dimensional array, which has each element as key -> value:
array(array(id,1),array(name,abcd),array(age,30))
Any advice would be appreciated!
I tried this code:
foreach ($datatest as $lines => $value){
$tok = explode(',',$value);
$arrayoutput[$tok[0]][$tok[1]] = $value;
}
but it didn't work.
Assuming you want to remove all quotation marks as per your question:
$oldArray = array('id,"1"', 'name,"abcd"', 'age,"30"')
$newArray = array();
foreach ($oldArray as $value) {
$value = str_replace(array('"',"'"), '', $value);
$parts = explode(',', $value);
$newArray[] = $parts;
}
You can do something like this:
$a = array('id,"1"', 'name,"abcd"', 'age,"30"');
$b = array();
foreach($a as $first_array)
{
$temp = explode("," $first_array);
$b[$temp[0]] = $b[$temp[1]];
}
$AR = array('id,"1"', 'name,"abcd"', 'age,"30"');
$val = array();
foreach ($AR as $aa){
$val[] = array($aa);
}
print_r($val);
Output:
Array ( [0] => Array ( [0] => id,"1" ) [1] => Array ( [0] => name,"abcd" ) [2] => Array ( [0] => age,"30" ) )
With array_map function:
$arr = ['id,"1"', 'name,"abcd"', 'age,"30"'];
$result = array_map(function($v){
list($k,$v) = explode(',', $v);
return [$k => $v];
}, $arr);
print_r($result);
The output:
Array
(
[0] => Array
(
[id] => "1"
)
[1] => Array
(
[name] => "abcd"
)
[2] => Array
(
[age] => "30"
)
)

Array difference for multidimensional array with single array in php

I want difference of multidimensional array with single array. I dont know whether it is possible or not. But my purpose is find diference.
My first array contain username and mobile number
array1
(
array(lokesh,9687060900),
array(mehul,9714959456),
array(atish,9913400714),
array(naitik,8735081680)
)
array2(naitik,atish)
then I want as result
result( array(lokesh,9687060900), array(mehul,9714959456) )
I know the function array_diff($a1,$a2); but this not solve my problem. Please refer me help me to find solution.
Try this-
$array1 = array(array('lokesh',9687060900),
array('mehul',9714959456),
array('atish',9913400714),
array('naitik',8735081680));
$array2 = ['naitik','atish'];
$result = [];
foreach($array1 as $val2){
if(!in_array($val2[0], $array2)){
$result[] = $val2;
}
}
echo '<pre>';
print_r($result);
Hope this will help you.
You can use array_filter or a simple foreach loop:
$arr = [ ['lokesh', 9687060900],
['mehul', 9714959456],
['atish', 9913400714],
['naitik', 8735081680] ];
$rem = ['lokesh', 'naitik'];
$result = array_filter($arr, function ($i) use ($rem) {
return !in_array($i[0], $rem); });
print_r ($result);
The solution using array_filter and in_array functions:
$array1 = [
array('lokesh', 9687060900), array('mehul', 9714959456),
array('atish', 9913400714), array('naitik', 8735081680)
];
$array2 = ['naitik', 'atish'];
$result = array_filter($array1, function($item) use($array2){
return !in_array($item[0], $array2);
});
print_r($result);
The output:
Array
(
[0] => Array
(
[0] => lokesh
[1] => 9687060900
)
[1] => Array
(
[0] => mehul
[1] => 9714959456
)
)
The same can be achieved by using a regular foreach loop:
$result = [];
foreach ($array1 as $item) {
if (!in_array($item[0], $array2)) $result[] = $item;
}

Get only Numeric values from Array in PHP

I have an array that looks something like this:
Array (
[0] => Array ( [country_percentage] => 5 %North America )
[1] => Array ( [country_percentage] => 0 %Latin America )
)
I want only numeric values from above array. I want my final array like this
Array (
[0] => Array ( [country_percentage] => 5)
[1] => Array ( [country_percentage] => 0)
)
How I achieve this using PHP?? Thanks in advance...
When the number is in first position you can int cast it like so:
$newArray = [];
foreach($array => $value) {
$newArray[] = (int)$value;
}
I guess you can loop the 2 dimensional array and use a preg_replace, i.e.:
for($i=0; $i < count($arrays); $i++){
$arrays[$i]['country_percentage'] = preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
Ideone Demo
Update Based on your comment:
for($i=0; $i < count($arrays); $i++){
if( preg_match( '/North America/', $arrays[$i]['country_percentage'] )){
echo preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
}
Try this:
$arr = array(array('country_percentage' => '5 %North America'),array("country_percentage"=>"0 %Latin America"));
$result = array();
foreach($arr as $array) {
$int = filter_var($array['country_percentage'], FILTER_SANITIZE_NUMBER_INT);
$result[] = array('country_percentage' => $int);
}
Try this one:-
$arr =[['country_percentage' => '5 %North America'],
['country_percentage' => '0 %Latin America']];
$res = [];
foreach ($arr as $key => $val) {
$res[]['country_percentage'] = (int)$val['country_percentage'];
}
echo '<pre>'; print_r($res);
output:-
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You can use array_walk_recursive to do away with the loop,
passing the first parameter of the callback as a reference to modify the initial array value.
Then just apply either filter_var or intval as already mentioned the other answers.
$array = [
["country_percentage" => "5 %North America"],
["country_percentage" => "0 %Latin America"]
];
array_walk_recursive($array, function(&$value,$key){
$value = filter_var($value,FILTER_SANITIZE_NUMBER_INT);
// or
$value = intval($value);
});
print_r($array);
Will output
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You could get all nemeric values by looping through the array. However I don't think this is the most efficient and good looking answer, I'll post it anyways.
// Array to hold just the numbers
$newArray = array();
// Loop through array
foreach ($array as $key => $value) {
// Check if the value is numeric
if (is_numeric($value)) {
$newArray[$key] = $value;
}
}
I missunderstood your question.
$newArray = array();
foreach ($array as $key => $value) {
foreach ($value as $subkey => $subvalue) {
$subvalue = trim(current(explode('%', $subvalue)));
$newArray[$key] = array($subkey => $subvalue);
}
}
If you want all but numeric values :
$array[] = array("country_percentage"=>"5 %North America");
$array[] = array("country_percentage"=>"3 %Latin America");
$newArray = [];
foreach ($array as $arr){
foreach($arr as $key1=>$arr1) {
$newArray[][$key1] = intval($arr1);
}
}
echo "<pre>";
print_R($newArray);
This is kind of a ghetto method to doing it cause I love using not as many pre made functions as possible. But this should work for you :D
$array = array('jack', 2, 5, 'gday!');
$new = array();
foreach ($array as $item) {
// IF Is numeric (each item from the array) will insert into new array called $new.
if (is_numeric($item)) { array_push($new, $item); }
}

Sort array according to first array

I have this array $arr1
Array
(
[0] => [col1]
[1] => [col2]
[2] => [col3]
)
I have another array $arr2 as
Array
(
[0] => Array
(
[col3] => data1
[col2] => data2
[col1] => data3
)
[1] => Array
(
[col2] => data1
[col3] => data2
[col1] => data3
)
)
I need to sort this $arr2 keys as col1, col2 and col3 like as it is on $arr1.
I tried with array_multisort($arr1,$arr2) and the other way. Nothing worked. any help on this ?
Using loop.
$keys = array_values($arr1);
$out = array();
foreach($arr2 as $ar){
$outar = array();
foreach($keys as $k){
if(isset($ar[$k])){
$outar[$k]=$ar[$k];
}
}
$out[]=$outar;
}
The output array will be held in $out. See ideone.
You can do this with uksort and a closure (PHP 5.3+)
foreach($arr2 as &$array){
uksort($array,function($a,$b) use ($arr1){
return array_search($a, $arr1) - array_search($b, $arr1);
});
}
foreach ( $arr2 as $k => &$arr ) {
ksort($arr);
}
print_r($arr2);
Use ksort with a foreach loop with value passed by reference.
if first array values are exactly the same as indexes in second one, try
$resarr = array();
foreach ($arr2 as $somearr) {
$i = 0;
$newarr = array();
foreach ($somearr as $value) {
$newarr[$arr1[$i]] = $value;
$i++;
}
$resarr[] = $newarr;
}
$arr1 = $resarr;

PHP convert one dimensional array into multidimensional

I have one array as
$tmpArr = array('A', 'B', 'C');
I want to process this array and want new array as
$tmpArr[A][B][C] = C
I.e last element becomes the value of final array.
Can anyone suggest the solution? Please help. Thanks in advance
Iterate the array of keys and use a reference for the end of the chain:
$arr = array();
$ref = &$arr;
foreach ($tmpArr as $key) {
$ref[$key] = array();
$ref = &$ref[$key];
}
$ref = $key;
$tmpArr = $arr;
$tmpArr = array('A', 'B', 'C');
$array = array();
foreach (array_reverse($tmpArr) as $arr)
$array = array($arr => $array);
Output:
Array
(
[A] => Array
(
[B] => Array
(
[C] => Array
(
)
)
)
)
$tmpArr[$tmpArr[0]][$tmpArr[1]][$tmpArr[2]] = $tmpArr[2];
Is that what you want?

Categories