I have a few associative arrays that I need to merge together based on there key.
so:
array1:
[person1] => tony
[person2] => sandra
array2:
[person1] => london
[person2] => paris
needs to be :
array 3
[person1] => tony , london
[person2] => sandra , paris
The issue I'm having though is that the key could be any value , so it could be 'person1' or it could be 'hairyOtter' and the array is of varaible size.
Assuming, that every is not multi-dimensional
$merged = array_merge_recursive($array1, $array2);
foreach ($merged as &$entry) {
if (is_array($entry)) {
$entry = implode(', ', $entry);
}
}
The idea is, that array_merge_recursive() creates a new array, if it find two values with the same key. Everything else stays untouched.
I'm sure there are more efficient ways to accomplish this, but for now, this works:
<?php
function combine( $keys, $first, $second ) {
$args = func_get_args( );
$keys = array_shift( $args );
$arrays = $args;
$result = array( );
foreach( $keys as $key ) {
foreach( $arrays as $array ) {
if( isset( $array[$key] ) ) {
$result[$key][] = $array[$key];
}
}
}
return $result;
}
$first = array(
'person1' => 'tony',
'person2' => 'sandra'
);
$second = array(
'person1' => 'london',
'person2' => 'paris'
);
/**
* To make sure you get *every* key out of both arrays.
*/
$keys = array_unique( array_merge( array_keys( $first ), array_keys( $second ) ) );
$combined = combine( $keys, $first, $second );
var_dump( $combined );
Two loops should do it. Iterate over each of array1 and array2, initialising array3's keys as you go to an array, and pushing into that array. Here's the first loop
$array3 = array();
foreach (array_keys($array1) as $key) {
if(!array_key_exists($key, $array3)) {
$array3[$key] = array();
}
array_push($array3[$key], $array1[$key]);
}
$array1 = array('a' => 1, 'b' => 2);
$array2 = array('a' => 3, 'b' => 4, 'c' => 5);
foreach ($array1 as $k => $v) {
$tArray[$k][] = $v;
}
foreach ($array2 as $k => $v) {
$tArray[$k][] = $v;
}
foreach ($tArray as $k => $v) {
$tArray[$k] = implode(',',$tArray[$k]);
}
I would create a multi-dimensional array instead, unless there is a specific reason you can't use one. This way, you would have an array that looks like:
Array
(
[Person1] => Array
(
[Name] => Tony
[City] => London
)
[Person2] => Array
(
[Name] => Sandra
[City] => Paris
)
)
Related
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); }
}
I want to delete an index from array and insert it into in new array. I want two things which i tried to explain one is
Array
(
[index1] => Deleted
[index4] => Inserted
)
Array
(
[index3] => test
[index4] => Inserted
)
Array
(
[index2] => numbers
[index3] => test
[index4] => Inserted
)
Array
(
[index1] => Deleted
)
now i want if arraysize is 1
foreach($array as $arrays){
array_push($array1,($arrays[0]));
unset ($arrays[0]);
}
i want to remove
Array
(
[index1] => Deleted
)
from $array and $array to be
[index1] => Deleted
second is if $array is
Array
(
[index2_123] => numbers
[index3_level] => test
[index4_test] => Inserted
)
i want a new array with $array1 as
Array
(
[index3_level] => test
)
and $array1 is modified to
Array
(
[index2_123] => numbers
[index4_test] => Inserted
)
Try this way,
$arr = Array
(
'index1' => 'Deleted',
'index2' => 'numbers',
'index3' => 'test',
'index4' => 'Inserted'
);
$arr1 = $arr2 = array();
$i = 0;
foreach($arr as $key => $value){
if($i%2 == 0){
$arr1[$key] = $value;
}else{
$arr2[$key] = $value;
}
$i++;
}
Output
$arr1
Array
(
[index1] => Deleted
[index3] => test
)
$arr2
Array
(
[index2] => numbers
[index4] => Inserted
)
And if you don't need that value then you can use it as
$i = 0;
foreach($arr as $key => $value){
if($i%2 == 0){
$arr[$key] = $value;
}else{
unset($arr[$key]);
}
$i++;
}
print_r($arr);
Output:
Array
(
[index1] => Deleted
[index3] => test
)
Loop through them and generate the array -
$new = array();
foreach($yourarray as $key => $val) {
$index = str_replace('index', '', $key); // get the key index
if($index % 2 != 0) { // check for odd or even
$new[$key] = $val; // set the new array
unset($yourarray[$key]); // delete from the main array
}
}
Update
For any index use a counter
$i = 0;
$new = array();
foreach($yourarray as $key => $val) {
if($i % 2 != 0) { // check for odd or even
$new[$key] = $val; // set the new array
unset($yourarray[$key]); // delete from the main array
}
$i++;
}
You can use a combination of array_flip and array_diff_key to filter the first array, then use array_diff filter the second:
$specificIndex = array('index1', 'index3');
$array1 = array_diff_key($array, array_flip($specificIndex));
$array2 = array_diff($array, $array1);
Demo.
If you want get in an array only certain elements of your choice you can do something like:
$specificIndex = array('index1', 'index3');
$selectedItem = array_intersect_key($array, array_flip($specificIndex));
Demo.
<?php
$array = array(
'index1' => 'Deleted',
'index2' => 'numbers',
'index3' => 'test',
'index4' => 'Inserted',
);
$specificIndex = 'index3';
$array1=array();
foreach($array as $key => $value){
if($key==$specificIndex){
$array1[$key] = $value;
unset($array[$specificIndex]);
}
}
print_r($array);
print_r($array1);
http://3v4l.org/TvZ19
I got main array keys a1 and a2.
$array1 = array(a1=>array(200,300,300), a2=>array(100,600,200));
$array2 = array(a1=>array('gen','gen2','gen'), a2=>array('gen2','gen3','gen3'));
I want my output to be
'a1'=>array(
'gen'=>200
'gen2'=>300
'gen'=>300
),
'a2'=>array(
'gen2'=>100
'gen3' =>600
'gen3' =>200
)
or
'a1'=>array(
'gen'=>500
'gen2'=>300
)
'a2'=>array(
'gen2'=>100
'gen3'=>800
)
I have tried this code but not enough, It doesn''t show the duplicate or it's better if it shows the sum of of the value ofduplicate keys
<?php
$array1 = array(a1=>array(200,300,300), a2=>array(100,600,200));
$array2 = array(a1=>array('gen','gen2','gen'), a2=>array('gen2','gen3','gen3'));
$result = array();
foreach($array1 as $k => $v) {
$result[$k] = array_combine($array2[$k], $v);
}
print_r($result);
?>
Thanks you very much for your help
$array1 = array(
'a1' => array(200,300,300),
'a2' => array(100,600,200));
$array2 = array(
'a1' => array('gen','gen2','gen'),
'a2' => array('gen2','gen3','gen3'));
$result = array('a1' => array(), 'a2' => array());
foreach($array2 as $k => $v) {
foreach ($v as $k2 => $v2){
if (array_key_exists($v2, $result[$k])){
$result[$k][$v2] += $array1[$k][$k2];
} else {
$result[$k][$v2] = $array1[$k][$k2];
}
}
}
Output:
Array
(
[a1] => Array
(
[gen] => 500
[gen2] => 300
)
[a2] => Array
(
[gen2] => 100
[gen3] => 800
)
)
I want to implode this array to make a string with all keys = 'Palabra'. How can this be done? (the output should be: 'juana es')
Array
(
[0] => Array
(
[Palabra] => juana
)
[1] => Array
(
[Palabra] => es
[0] => Array
(
[Raiz] => ser
[Tipo] => verbo
[Tipo2] => verbo1
)
)
)
function foo( $needly, $array ) {
$results = array();
foreach ( $array as $key => $value ) {
if ( is_array( $value ) ) {
$results = array_merge($results, foo( $needly, $value ));
} else if ( $key == $needly ) {
$results[] = $value;
}
}
return $results;
}
echo implode( " ", foo( "Palabra", $your_array ) );
I ended using the foreach for lack of a better solution:
foreach ($array as $key => $palabra) {
$newArray[] = $array[$key]["Palabra"];
}
$string = implode(' ', $newArray);
I think the simplest solution is with array_walk_recursive.
<?php
$arr = array(
array(
'Palabra' => 'juana',
),
array(
'Palabra' => 'es',
array(
'Raiz' => 'ser',
'Tipo' => 'verbo',
'Tipo2' => 'verbo1',
),
),
);
$str = array();
array_walk_recursive($arr, function($value, $key) use(&$str) {
if ($key == 'Palabra') {
$str[] = $value;
}
});
$str = implode(' ', $str);
echo "$str\n";
The function passed in is called for each key-value pair in the array and any subarrays. Here we append any values with a matching key to an array and then implode the array to get a string.
I'm trying to figure out how to sort an array by the value of the last key, when the number of keys are unknown?
So, if I have arrays that look like this:
Array(
[0] => Array(
[0] => Bob
[1] => A
[2] => Parker
)
[1] => Array(
[0] => John
[1] => Smith-Doe
)
[2] => Array(
[0] => Giuseppe
[1] => Gonzalez
[2] => Octavio
[3] => Hernandez
)
)
I want to sort it by the last value in the array:
Giuseppe Gonzalez Octavio Hernandez
Bob A. Parker
John Smith-Doe
$arr = array(
array('Bob', 'A', 'Parker'),
array('John', 'Smith-Doe'),
array('Giuseppe', 'Gonzalez', 'Octavio', 'Hernandez')
);
usort($arr, 'sort_by_last_item');
var_dump($arr);
function sort_by_last_item($a, $b)
{
return end($a) > end($b);
}
or if you're using php 5.3:
$arr = array(
array('Bob', 'A', 'Parker'),
array('John', 'Smith-Doe'),
array('Giuseppe', 'Gonzalez', 'Octavio', 'Hernandez')
);
usort($arr, function($a, $b) { return end($a) > end($b); });
var_dump($arr);
$data = array( /* your data */ );
$output = array();
foreach ( $data as $v ) {
$output[ end($v) ] = $v;
}
ksort($output);
var_dump($output);
alternatively:
$data = array( /* your data */ );
$output = array();
foreach ( $data as $v ) {
$key = implode(' ', array_reverse($v));
$output[ $key ] = $v;
}
ksort($output);
var_dump($output);
Second method allow you to have many records with the same last element and sorts by last elements, and if they are equals - sort by first before last and so on...
This works:
function array_last_item_sort($array){
$return = array();
$sort = array();
foreach($array as $i => $item){
$sort[$i] = $item[count($item) - 1];
}
asort($sort);
foreach($sort as $i => $value){
$return[] = $array[$i];
}
return $return;
}