Update Multidimentional Array with another Array for existing Keys PHP - php

I have two arrays:
('admin','admin2', 'admin3' can be too many, and names can also differ other than 'admin')
$old = array(
array('admin'=>array('a'=>'aaa','b'=>'bbb')),
array('admin2'=>array('c'=>'ccc','d'=>'ddd'))
);
$new = array(
array('admin2'=>array('e'=>'eee','f'=>'fff')),
array('admin3'=>array('g'=>'ggg','h'=>'hhh'))
);
I want to have this array from both above arrays:
(new array with all different keys in both PLUS similar keys from new array)
$output = array(
array('admin'=>array('a'=>'aaa','b'=>'bbb')),
array('admin2'=>array('e'=>'eee','f'=>'fff')),
array('admin3'=>array('g'=>'ggg','h'=>'hhh'))
);

// Remove one level of array to make arrays as ['admin'=>array, 'admin2'=>array]
$old1 = call_user_func_array('array_merge', $old);
$new1 = call_user_func_array('array_merge', $new);
// Make replacement
$ready = array_replace($old1, $new1);
// Return level making every item as array
$result = array();
foreach($ready as $k=>&$v)
$result[] = array($k=>$v);
print_r($result);
demolink

This code will solve your problem :
<?php
$array1 = array(
array('admin'=>array('a'=>'aaa','b'=>'bbb')),
array('admin2'=>array('c'=>'ccc','d'=>'ddd'))
);
$array2 = array(
array('admin2'=>array('e'=>'eee','f'=>'fff')),
array('admin3'=>array('g'=>'ggg','h'=>'hhh'))
);
$output = $array1; ///merge array1 into output array
foreach($array2 as $key => $val)
{
$is_present_key = false;
$first_key = key($val);
foreach($output as $k => $v)
{
if(array_key_exists($first_key,$output[$k])) ////check if key exit in $output array
{
$output[$k] = $val; ///push new value if key exists in $output
$is_present_key = true;
}
}
if($is_present_key == false)///skip for duplicate of new values if key exists in $output
{
$output[] = $val;
}
}
echo "<pre>"; print_r($output);
?>
This will give you :
Array
(
[0] => Array
(
[admin] => Array
(
[a] => aaa
[b] => bbb
)
)
[1] => Array
(
[admin2] => Array
(
[e] => eee
[f] => fff
)
)
[2] => Array
(
[admin3] => Array
(
[g] => ggg
[h] => hhh
)
)
)
LIVE EXAMPLE

$old = array(
array('admin'=>array('a'=>'aaa','b'=>'bbb')),
array('admin2'=>array('c'=>'ccc','d'=>'ddd'))
);
$new = array(
array('admin2'=>array('e'=>'eee','f'=>'fff')),
array('admin3'=>array('g'=>'ggg','h'=>'hhh'))
);
$arr=array_merge($new,$old);
$new_arr=array();
foreach($arr as $key=>$val){
foreach($val as $k=>$v){
if(array_key_exists($k, $new_arr)){
continue;
}else{
$new_arr[$k]=$v;
}
}
}
echo "<pre>";print_r($new_arr); echo "</pre>";

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"
)
)

transfer specific index of array to a new array - php

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

How to remove duplicate values from a multidimentional array according to a key

Simple question have following code but won't work
//Enter your code here, enjoy!
$correo[] = array('valor'=>'vikram.123#gmil.com','registro'=>'23');
$correo[] = array('valor'=>'vikram.123#gmil.com','registro'=>'24');
$correo[] = array('valor'=>'vikram.123#gmil.com','registro'=>'26');
function arrayUnique($myArray){
if(!is_array($myArray))
return $myArray;
foreach ($myArray as &$myvalue){
$myvalue=serialize($myvalue);
}
$myArray=array_unique($myArray);
foreach ($myArray as &$myvalue){
$myvalue=unserialize($myvalue);
}
return $myArray;
}
$arr= arrayUnique($correo);
var_dump($arr);
What I am trying to do is remove those row which has repetitive valor key for example the result of above array should be
Array (
[0] => Array (
[valor] => 'vikram.123#gmail.com'
[registro] => 24
)
)
You can do like this...
$correo[] = array('valor'=>'vikram.123#gmil.com','registro'=>'23');
$correo[] = array('valor'=>'vikram.123#gmil.com','registro'=>'24');
$correo[] = array('valor'=>'vikram.123#gmil.com','registro'=>'26');
function arrayUnique($myArray, $uniqueKeyName)
{
// Unique Array for return
$myReturnArray = array();
// Array with the md5 hashes
$arrayHashes = array();
foreach($myArray as $key => $item) {
$hash = md5(serialize($item[$uniqueKeyName]));
if (!isset($arrayHashes[$hash])) {
$arrayHashes[$hash] = $hash;
$myReturnArray[] = $item;
}
}
return $myReturnArray;
}
$arr= arrayUnique($correo, 'valor');
echo "<pre>";
print_r($arr);
echo "</pre>";
You may try like this, since you said any one of registro should be considered.
[akshay#localhost tmp]$ cat test.php
<?php
$array = array(
array('valor'=>'vikram.123#gmil.com','registro'=>'23'),
array('valor'=>'vikram.123#gmil.com','registro'=>'24'),
array('valor'=>'vikram.123#gmil.com','registro'=>'26')
);
function remove_dup($array, $key)
{
foreach( $array as $v )
{
if(! isset($out[ $v[$key] ] ) )
$out[$v[$key]] = $v;
}
return array_values($out);
}
// Input
print_r( $array );
// Output
print_r( remove_dup($array,'valor') );
?>
Output
[akshay#localhost tmp]$ php test.php
Array
(
[0] => Array
(
[valor] => vikram.123#gmil.com
[registro] => 23
)
[1] => Array
(
[valor] => vikram.123#gmil.com
[registro] => 24
)
[2] => Array
(
[valor] => vikram.123#gmil.com
[registro] => 26
)
)
Array
(
[0] => Array
(
[valor] => vikram.123#gmil.com
[registro] => 23
)
)
You can define the function like -
function arrayUnique($myArray){
if(!is_array($myArray))
return $myArray;
$temp = array();
foreach ($myArray as $myvalue){
$temp[$myvalue['valor']] = $myvalue;
}
return $temp;
}
Store the array with valor as key. It will store only the last one.

Don't want Array ito combine values

I Have an array in PHP that looks like:
Array ( [2099:360] => 6-3.25 [2130:361] => 4-2.5 [2099:362] => 14-8.75 )
Notice there is Two Keys that are 2099 and one that is 2130. I Have a foreach to remove the everything after the colon. the $drop is my array
$a = array();
foreach ($drop as $part=>$drop_a){
$ex_part = explode(":", $part);
$a[$ex_part[0]] = $drop_a;
}
print_r($a);
but when I print $a it displays only the recent value of the 2099?
Array ( [2099] => 14-8.75 [2130] => 4-2.5 )
Any Successions? How can I get it to display all of the values?
Thank You for Your Help
One solution is to use a multi-dimensional array to store this strategy:
$a = array();
foreach ($drop as $part=>$drop_a){
$ex_part = explode(":", $part);
if (isset($a[$ex_part[0]])) {
$a[$ex_part[0]][] = $drop_a;
} else {
$a[$ex_part[0]] = array($drop_a);
}
}
Your resulting data-set will however be different:
Array ( [2099] => Array ( [0] => 6-3.25 [1] => 14-8.75) [2130] => Array ( [0] => 4-2.5 ) )
It may be beneficial to you to preserve the second portion after the colon :
$a = array();
foreach ($drop as $part=>$drop_a){
$ex_part = explode(":", $part);
if (isset($a[$ex_part[0]])) {
$a[$ex_part[0]][$ex_part[1]] = $drop_a;
} else {
$a[$ex_part[0]] = array($ex_part[1] => $drop_a);
}
}
Now your result is a little more meaningful:
Array ( [2099] => Array ( [360] => 6-3.25 [362] => 14-8.75) [2130] => Array ( [361] => 4-2.5 ) )
Finally you can use alternative key-naming strategy if one is already occupied:
$a = array();
foreach ($drop as $part=>$drop_a){
$ex_part = explode(":", $part);
if (isset($a[$ex_part[0]])) {
$a[altName($ex_part[0], $a)] = $drop_a;
} else {
$a[$ex_part[0]] = $drop_a;
}
}
function altName($key, $array) {
$key++; // Or however you want to do an alternative naming strategy
if (isset($array[$key])) {
return altName($key, $array); // This will eventually resolve - but be careful with the recursion
}
return $key;
}
Returns:
Array
(
[2099] => 6-3.25
[2130] => 4-2.5
[2100] => 14-8.75
)
You basically have a key and a sub key for each entry, so just put them in a multidimensional array:
$a = array();
foreach ($drop as $key => $val) {
list($key, $subKey) = explode(':', $key);
$a[$key][$subKey] = $val;
}
Gives you:
Array
(
[2099] => Array
(
[360] => 6-3.25
[362] => 14-8.75
)
[2130] => Array
(
[361] => 4-2.5
)
)
You can traverse multidimensional arrays by nesting loops:
foreach ($a as $key => $subKeys) {
foreach ($subKeys as $subKey => $val) {
echo "$key contains $subKey (value of $val) <br>";
}
}

php - sort by value of last key in array?

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;
}

Categories