Ex :
First array:
Array
(
[0] => id
[1] => ADDRESS
[2] => ADDRESS1
[3] => name
)
Second array:
Array
(
[id] => 1
[name] => Ankit
[city] => SURAT
)
Required OUTPUT :
[id] => 1
[ADDRESS]=>
[ADDRESS1]=>
[name] => Ankit
here we can see that value of first array ADDRESS,ADDRESS1 doesn't exist in array 2 key,
so i need value to be set null for ADDRESS,ADDRESS1 and unnecessary field of array 2 is city which key doesn't exist in first array values is need to be unset from result array
CODE :
$field_arr= array('0'=>"id",
"1"=>"ADDRESS",
"2"=>"ADDRESS1",
'3'=>"name",
);
$arr=array("id"=>"1",
'name'=>"Ankit",
"city"=>"Ahmedabad");
$matching_fields =(array_diff_key(array_flip($field_arr),(array_intersect_key($arr,array_flip($field_arr)))));
if(!empty($matching_fields)){
foreach($matching_fields as $key=>$value){
$new_arr[$key]=null;
}
}
print_r($new_arr);
exit;
CURRENT OUTPUT OF NEW ARRAY :
Array
(
[ADDRESS] =>
[ADDRESS1] =>
)
but this is long process.as well as performance also matter. i want whole code reconstruct which i have made and just get output which is required output
Here some more need help need i want same sequence of key of output array same as first array value
my required output :
[id] => 1
[ADDRESS]=>
[ADDRESS1]=>
[name] => Ankit
current output :
[id] => 1
[name] => Ankit
[ADDRESS]=>
[ADDRESS1]=>
Thanks in advance
Just try with:
$keys = array('id', 'name', 'ADDRESS', 'ADDRESS1');
$data = array(
'id' => 1,
'name' => 'Ankit',
'city' => 'SURAT',
);
$output = $data + array_fill_keys($keys, null);
Output:
array (size=5)
'id' => int 1
'name' => string 'Ankit' (length=5)
'city' => string 'SURAT' (length=5)
'ADDRESS' => null
'ADDRESS1' => null
$keys = array_unique(array_merge($field_arr, array_keys($arr)));
$new_array = array();
foreach ($keys as $key)
{
$new_array[$key] = isset($arr[$key]) ? $arr[$key] : '';
}
echo "<pre>";
print_r($new_array);
You can use following;
$first = array(
"id",
"name",
"ADDRESS",
"ADDRESS1"
);
$second = array(
"id" => "1",
"name" => "Ankit",
"city" => "SURAT"
);
foreach ($first as $key) {
if ($second[$key] == null) {
$second[$key] = null;
}
}
var_dump($second);
Here is working demo: Demo
Related
I got the follwing array and I would like to retrieve the name by the id:
Array
(
[0] => Array
(
[id] => 1
[name] => john
)
[1] => Array
(
[id] => 2
[name] => mark
)
etc...
It is doable with double foreach loop and a conditional test, but is there a more elegant way?
Assuming that id is unique...
Long Version
$arr = [
['id'=1, 'name'='john'],
['id'=2, 'name'='mark'],
];
$lookup = [];
foreach($arr as $row) {
$id = $row['id'];
$name = $row['name'];
$lookup[$id] = $name;
}
// find name for id, 2
echo $lookup[2];
// ==> mark
Short Version
...see Progrock’s solution!
You can use array_column to map ids to names:
<?php
$arr = [
['id' => 1, 'name' => 'Rolf'],
['id' => 3, 'name' => 'Gary'],
['id' => 2, 'name' => 'Jimmy'],
];
$id_names = array_column($arr, 'name', 'id');
var_export($id_names);
print $id_names[3];
Output:
array (
1 => 'Rolf',
3 => 'Gary',
2 => 'Jimmy',
)Gary
I want to remove array from multidimentional array using base of ID. I tried using foreach loop. But, It is not working.
Any one help me how to remove this?
Thanks.
=> Array :
Array
(
[0] => Array
(
[id] => 11109
[value] => Yes
[field_id] => 234
)
[1] => Array
(
[id] => 11109
[value] => Yes
[field_id] => 237
)
[2] => Array
(
[id] => 11110
[value] => No
[field_id] => 234
)
[3] => Array
(
[id] => 11110
[value] => No
[field_id] => 237
)
[4] => Array
(
[id] => 11111
[value] => No
[field_id] => 237
)
)
From this array, I want to remove array which
field_id is 234 and value is "No" && field_id is 237 and value is
"No".
field_id is 234 and value is "Yes" && field_id is 237 and value is
"Yes".
So, From this array only ID 11111 array is display otherwise all array remove from current array.
Here is my code using I tried to remove array.
foreach ($collection->getData() as $key => $value) {
if(($value['field_id'] == $ids[0] && $value['value'] == "No")){
echo $value['id'];
// exit;
break;
}
echo $value['field_id'];
echo $value['value'];
if(($value['field_id'] == $ids[1] && $value['value'] == "No")){
print_r($collection->getData()[$key]);
unset($collection->getData()[$key]);
unset($collection->getData()[$key-1]);
}
}
You can create a new Multidimensional array , and copy only the values you want to it .
also , when you use break , you get out of the foreach loop completely , i don't think this is the intended behavior , use continue to skip current iteration and test the next element
Is the function getData() returning a copy of the array or a reference? If is is only a copy the unset($collection->getData()[$key]) won't work.
Better you loop over the array as you do, but store all keys you want to delete in side a other array (e.g. $keysToRemove). When the for-each-loop is finished you start to loop the new array $keysToRemove containing all the keys you want to remove and remove then from array.
$keysToRemove = array();
$data = $collection->getData(); // copy or reference?
foreach ($data as $key => $value) {
if(($value['field_id'] == $ids[0] && $value['value'] == "No")){
echo $value['id'].'<br>';
break; // exit the loop? If you want to jump to the next element use "continue"
}
echo $value['field_id'].'<br>';
echo $value['value'].'<br>';
if(($value['field_id'] == $ids[1] && $value['value'] == "No")){
$keysToRemove[$key] = true;
$keysToRemove[$key-1] = true;
}
}
foreach(array_keys($keysToRemove) as $key){
echo '<p>remove key '.$key.' with content <pre>'.print_r($data[$key], true).'</pre></p>';
unset($data[$key]);
}
echo '<p>Result array is<pre>'.print_r($data, true).'</pre></p>';
So you don't manipulate the array your loop use at the moment.
Based on the comment that mentioned its a Magento Collection. I think, You could filter the ids in collection itself so that those are not fetched as part of the collection you want. Like:
$collection = Mage::getModel('your/model')->getCollection();
$collection->addAttributeToFilter('field_id', array('nin' => array(234, 237)));
OR, following if your model is non-eav entity model
$collection = Mage::getModel('your/model')->getCollection();
$collection->addFieldToFilter('field_id', array('nin' => array(234, 237)));
try this code which remove all array value which value is No
$cart = array(
0 => array
(
'id' => 11109,
'value' => 'Yes',
'field_id' => 234
),
1 => array
(
'id' => 11109,
'value' => 'Yes',
'field_id' => 123
),
2 => array
(
'id' => 11110,
'value' => 'No',
'field_id' => 234
),
3 => array
(
'id' => 11110,
'value' => 'No',
'field_id' => 237
),
4 => array
(
'id' => 11111,
'value' => 'No',
'field_id' => 237
),
);
$found = array();
$i = 0;
foreach ($cart as $key => $data) {
if ($data['field_id'] == 234 && $data['value'] == 'No') {
$found[$i]['id'] = $data['id'];
$found[$i]['value'] = $data['value'];
$found[$i]['field_id'] = $data['field_id'];
$i++;
}
}
echo "<pre>";
print_r($found);
then Output Is:
Array
(
[0] => Array
(
[id] => 11111
[value] => No
[field_id] => 234
)
)
I have an array in PHP code below, and I want to convert this array to be grouped by data value. It's always hard to simplify arrays.
Original array:
Array
(
[0] => Array
(
[date] => 2017-08-22
[AAA] => 1231
)
[1] => Array
(
[date] => 2017-08-21
[AAA] => 1172
)
[2] => Array
(
[date] => 2017-08-20
[AAA] => 1125
)
[3] => Array
(
[date] => 2017-08-21
[BBB] => 251
)
[4] => Array
(
[date] => 2017-08-20
[BBB] => 21773
)
[5] => Array
(
[date] => 2017-08-22
[CCC] => 3750
)
[6] => Array
(
[date] => 2017-08-20
[CCC] => 321750
)
)
Below is my desired array:
Array
(
[2017-08-22] => Array
(
[AAA] => 1231
[CCC] => 3750
)
[2017-08-21] => Array
(
[AAA] => 1172
[BBB] => 251
)
[2017-08-20] => Array
(
[AAA] => 1125
[BBB] => 21773
[CCC] => 321750
)
)
It is also ok to have empty null value if the data doesn't exist. [BBB] => NULL for 2017-08-22.
Can anybody help? Thanks in advance...
A simple loop should do this..
$group = [];
foreach ($data as $item) {
if (!isset($group[$item['date']])) {
$group[$item['date']] = [];
}
foreach ($item as $key => $value) {
if ($key == 'date') continue;
$group[$item['date']][$key] = $value;
}
}
Here : this should do the work.
$dst_array = array();
foreach ($array as $outerval) {
foreach ($outerval as $key => $innerval) {
if ($key != 'date') {
$dst_array[$outerval['date']][$key] = $innerval;
}
}
}
It iterates through the array and then through the entries in each subarray. Any any that is not a date is assigned in the destination array in the subarray corresponding to its date and with its own current key.
I definitely wouldn't recommend any techniques that involve more than one loop -- this process can certainly be performed in a single loop.
If you like language construct iteration, use a foreach() loop: (Demo)
$result = [];
foreach ($array as $row) {
$date = $row['date'];
unset($row['date']);
$result[$date] = array_merge($result[$date] ?? [], $row);
}
var_export($result);
If you like to use functional programming and fewer global variables, use array_reduce(): (Demo)
var_export(
array_reduce(
$array,
function($accumulator, $row) {
$date = $row['date'];
unset($row['date']);
$accumulator[$date] = array_merge($accumulator[$date] ?? [], $row);
return $accumulator;
},
[]
)
);
These techniques unconditionally push data into the subarray with the key based on the date column value.
The above technique will work consistently even if the order of your subarray elements changes.
The ?? (null coalescing operator) is to ensure that array_merge() always has an array in the first parameter -- if processing the first occurrence of a given date, you simply merge the current iteration's data (what's left of it after unset() removes the date element) with an empty array.
I believe this solution will work for you:
<?php
$array = Array
(
0 => Array
(
'date' => '2017-08-22',
'AAA' => '1231',
),
1 => Array
(
'date' => '2017-08-21',
'AAA' => '1172',
),
2 => Array
(
'date' => '2017-08-20',
'AAA' => '1125'
),
3 => Array
(
'date' => '2017-08-21',
'BBB' => '251'
),
4 => Array
(
'date' => '2017-08-20',
'BBB' => '21773',
),
5 => Array
(
'date' => '2017-08-22',
'CCC' => '3750'
),
6 => Array
(
'date' => '2017-08-20',
'CCC' => '321750'
)
);
echo '<pre>';
$array1 = array('AAA' => null, 'BBB' => null, 'CCC' => null);
$array2 = array();
array_walk($array, function ($v) use (&$array2, $array1) {
$a = $v['date'];
if (!isset($array2[$a])) {
$array2[$a] = $array1;
}
unset($v['date']);
$array2[$a] = array_merge($array2[$a], $v);
});
print_r($array2);
Output
Array
(
[2017-08-22] => Array
(
[AAA] => 1231
[BBB] =>
[CCC] => 3750
)
[2017-08-21] => Array
(
[AAA] => 1172
[BBB] => 251
[CCC] =>
)
[2017-08-20] => Array
(
[AAA] => 1125
[BBB] => 21773
[CCC] => 321750
)
)
check output at: https://3v4l.org/NvLB8
Another approach (quick & dirty) making use of an arrays internal pointer:
$newArray = [];
foreach ($array as $childArray) {
$date = current($childArray);
$value = next($childArray); // this advances the internal pointer..
$key = key($childArray); // ..so that you get the correct key here
$newArray[$date][$key] = $value;
}
This of course only works with the given array structure.
Another perfect usage example for the PHP function array_reduce():
// The input array
$input = array(
0 => array(
'date' => '2017-08-22',
'AAA' => '1231',
),
// The rest of your array here...
);
$output = array_reduce(
$input,
function (array $carry, array $item) {
// Extract the date into a local variable for readability and speed
// It is used several times below
$date = $item['date'];
// Initialize the group for this date if it doesn't exist
if (! array_key_exists($date, $carry)) {
$carry[$date] = array();
}
// Remove the date from the item...
// ...and merge the rest into the group of this date
unset($item['date']);
$carry[$date] = array_merge($carry[$date], $item);
// Return the partial result
return $carry;
},
array()
);
The question is not clear. What is the expected result if one key (AAA f.e) is present on two or more dates? This answer keeps only the last value associated with it.
How can I delete an array index by comparing it to another array index?
PHP:
$results = array ( array(
"Name" => $NameUser,
"Surname" => $SurnameUser,
"MyComment" => $MyComment,
"VideoPath" => $VideoPath,
"Reg_Date" => $Reg_Date,
"ThumbPath" => $ThumbPath,
"UserId" => $UserId
));
print_r($results[0]); // Array ( [Name] => aaa [Surname] => aaa [MyComment] => aaa [VideoPath] => aaa [Reg_Date] => aaa [ThumbPath] => aaa [UserId] => aaa)
$JSON_List = file_get_contents('test.json');
$arr = json_decode($JSON_List);
print_r($arr[0]); // stdClass Object ( [Name] => aaa [Surname] => aaa [MyComment] => aaa [VideoPath] => aaa [Reg_Date] => aaa [ThumbPath] => aaa [UserId] => aaa )
I can see these two indexes are identical, I am using a for loop but it seeks that php are not seeing them as identical.
How can I compare the array properly and if identical remove the identical array index from the list?
PHP:
foreach ($arr as $index) {
$countIndex++;
print_r($countIndex);
if ($arr[$countIndex - 1] == $results[0]) {
print_r("array is identical \n");
}else{
print_r("array is not identical \n");
}
}
A simple way to check if two keys are present in two separate arrays is using the array_intersect_key() function.
$sameKeys = array_intersect_key($arr1, $arr2);
Having 2 arrays:
$results = array ( array(
"Name" => '$NameUser',
"Surname" => '$SurnameUser',
"MyComment" => '$MyComment',
"VideoPath" => '$VideoPath',
"Reg_Date" => '$Reg_Date',
"ThumbPath" => '$ThumbPath',
"UserId" => '$UserId'
)
);
// print_r($results[0]);
//$JSON_List = file_get_contents('test.json');
//$arr = json_decode($JSON_List);
$arr = array(array(//simulate
"Name" => '$NameUser',
"Surname" => '$SurnameUser',
"MyComment" => '$MyComment',
"VideoPath" => '$VideoPath',
"Reg_Date" => '$Reg_Date',
"ThumbPath" => '$ThumbPath',
"UserId" => '$UserId'
),
array(
"Name" => '$NameUser2',
"Surname" => '$SurnameUser2',
"MyComment" => '$MyComment2',
"VideoPath" => '$VideoPath2',
"Reg_Date" => '$Reg_Date2',
"ThumbPath" => '$ThumbPath',
"UserId" => '$UserId2'
));
//Search identicals
function search_identicals(&$arr,$results){
$response = array();
foreach($results as $k=>$value){
array_walk($arr,function($elem,$key)use($value,&$response,&$arr){
$resp = array_diff($elem,$value);
if(empty($resp)){
unset($arr[$key]);
array_push($response,$elem);
}
});
}
return ($response) ? $response : false;
}
$identicals = search_identicals($arr,$results);
var_dump('to delete');
var_dump($identicals);
var_dump('deleted');
var_dump($arr);
//You only need this:
function search_identicals(&$arr,$results){//&$arr by reference
foreach($results as $k=>$value){
array_walk($arr,function($elem,$key)use($value,&$arr){
$resp = array_diff($elem,$value);//if is identical, return empty
if(empty($resp)){
unset($arr[$key]);//remove repeated
}
});
}
}
You can use this: array_unique( array_merge($arr1, $arr2) );
OR this:
$arr_1 = array_diff($arr1, $arr2);
$arr_2 = array_diff($arr2, $arr1);
I need your help with my problem. My problem is I have 2 arrays the first one is the main array. The second is the array for my new data.
Let's say I have these arrays.
This is the main array:
Array
(
0 => Array
(
'id' => 1,
'name' => 'Apple',
'age' => 12
)
1 => Array
(
'id' => 2,
'name' => May,
'age' => 13
)
)
This is the second array:
Array
(
1 => Array
(
'gender' => 'Male'
)
2 => Array
(
'gender' => 'Female'
)
)
And I have this loop in PHP
foreach($main_array as &$main){
//this is the loop inside the first array
// how can I add the second array with it?
}
This is the sample output:
[0] => Array
(
[id] => 1
[name] => Apple
[age] => 12
[gender] => Female
)
[1] => Array
(
[id] => 2
[name] => May
[age] => 13
[gender] => Female
)
How can I do that? Any suggestions? That's all thanks.
for($i=0; $i<count($main_array); $i++){
for($j=0; $j<count($second_array); $j++){
if($main_array[$i]['id'] == $j){
$main_array[$i]['gender'] = $second_array[$j]['gender']
}
}
}
I fixed your example code, it wont run otherwise.
<?php
// Test data:
$main_array = Array(
0 => Array(
'id' => 1,
'name' => 'Apple',
'age' => 12
),
1 => Array (
'id' => 2,
'name' => 'May',
'age' => 13
)
);
$lookup = Array(
1 => Array(
'gender' => 'Male'
),
2 => Array(
'gender' => 'Female'
)
);
// Your answer:
foreach ($main_array as &$main) {
if (array_key_exists($main['id'],$lookup)) {
$main['gender'] = $lookup[$main['id']]['gender']; // <-- sets gender value
}
}
// Output it to browser:
echo '<pre>$main_array = '.print_r($main_array,true).'</pre>';
The array_key_exists() check is there to avoid errors such as PHP Notice: Undefined offset: 123 when the $lookup data is incomplete.
If you want to merge all of the data from both arrays:
PHP tools:
The exact behaviors of these functions needs to be studied and tested before usage, to make sure it fits your intent.
// array merge recursive doesn't merge numeric keys
$main_array = array_merge_recursive($main_array, $secondary_array);
// array replace recursive has a downside of replacing stuff
$main_array = array_replace_recursive($main_array, $secondary_array);
Rolling your own:
foreach($main_array as $i => &$main){
if(isset($secondary_array[$i])) {
foreach($secondary_array[$i] AS $key => $value) {
$main[$key] = $value;
}
}
}
Both of the above solutions only apply if the array-indexes of $main_array and $secondary_array match.
In your example your arrays don't match:
- $secondary_array[0] doesn't exist so $main_array[0] will not be populated with a 'gender' value;
- $main_array[2] doesn't exist so $main_array[2] will be created and it will only have a 'gender' value same as $secondary_array[2]['gender']
If you want to only merge some bits and pieces of the arrays:
Rolling your own:
foreach($main_array as $i => &$main) {
if(isset($secondary_array[$i])) and isset($secondary_array[$i]['gender'])) {
$main['gender'] = $secondary_array[$i]['gender'];
}
}
foreach($main_array as &$main){//this is the loop inside the first array
foreach($second_array as &$second){ //this is the loop inside the second array
}
}
foreach($arr1 as $k => $arr1Item) {
$arr1[$k]['gender'] = $arr2[$k]['gender'];
}