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);
Related
I want to change my array from, how can i make this kind of a change.
Array (
[0] => 53720
[1] => Array(
['Build Quality'] => 1=>10,
2=>9,
3=>7
['Versatality'] => 1=>9,
2=>8,
3=>7
['value'] => 1=>8,
2=>6,
3=>5
)
);
to:
Array (
53720 =>['Build Quality' => [1=>10,
2=>9,
3=>7],
'Versatality' => [1=>9,
2=>8,
3=>7],
'value' => [1=>8,
2=>6,
3=>5]
]
);
function get_array(){
$factor = array([0] => 'Build Quality' [1] => 'Versatality' [2] => 'Value');
$rank = array([0] => 1=>10,2=>9,3=>7 [1] => 1=>9,2=>8,3=>7 [2] => 1=>8,2=>6,3=>5);
$assoc_array = array_combine($factor, $rank);
$post_id = get_current_post_id(); //gives 53720
$result = array();
array_push($result, $post_id, $assoc_array);
print_r($result);
return $result[$post_id];
/* output: Array ([0] => 53720 [1] => Array (['Build Quality'] => 1=>10,2=>9,3=>7 ['Versatality'] => 1=>9,2=>8,3=>7 ['Value'] => 1=>8,2=>6,3=>5)) */
}
You can add elements to an associative array directly:
$result = [];
$result[$post_id] = $assoc_array;
You can also initiate one with keys and values directly:
$result = [
$post_id => $assoc_array
];
Also keep in mind that not any variable can be used as a key, as stated in the PHP documentation for arrays:
The key can either be an integer or a string. The value can be of any type.
I have an array with same customerid. I want to merge all same customerid arrays in to one with few amends to the array.
Array
(
[0] => Array
(
[customerid] => 13
[customer_fullname] => Chris
[profession_id] => 8
[profession_name] => Producer
)
[1] => Array
(
[customerid] => 1
[customer_fullname] => John
[profession_id] => 8
[profession_name] => Producer
)
[2] => Array
(
[customerid] => 13
[customer_fullname] => Chris
[profession_id] => 7
[profession_name] => Camera
)
)
So now I want a new array to be created like this:
Array(
[customerid] => 13
[customer_fullname] => Chris
[new_array] => array(
[0]=>[profession_id] => 8, [profession_name] => Producer,
[1]=>[profession_id] => 7, [profession_name] => Camera
)
)
Spent some time on it but wasn't able to get it right
There are better approaches if you're merging lots of records, but if you want a way to just merge two records as stated, I'd just do this:
$array1 = array(
'customerid' => 13
'customer_fullname' => 'John',
'profession_id' => 8,
'profession_name' => 'Producer'
);
$array2 = array(
'customerid' => 13
'customer_fullname' => 'John',
'profession_id' => 7,
'profession_name' => 'Director'
);
function merge_customers($customerA, $customerB)
{
$newCustomer = array();
if ($customerA['customerid'] == $customerB['customerid'])
{
$newCustomer['customerid'] = $customerA['customerid'];
$newCustomer['customer_fullname'] = $customerA['customer_fullname'];
$newCustomer['new_array'] = array(
array(
'profession_id' => $customerA['profession_id'],
'profession_name' => $customerA['profession_name']
),
array(
'profession_id' => $customerB['profession_id'],
'profession_name' => $customerB['profession_name']
)
);
return $newCustomer;
}
/* We can't merge these if they're different customers. */
return NULL;
}
The extended solution which is also well-suited for finding and "merging" multiple groups of entries which has same customerid. Used functions: array_filter, array_count_values, array_keys, array_walk, array_chunk and array_values:
// supposing $arr is your initial array
// finds which 'customerid' has multiple entries
$dupIds = array_filter(array_count_values(array_column($arr, "customerid")), function($v) {
return $v > 1;
});
$dupIds = array_keys($dupIds);
$result = [];
array_walk($arr, function($v) use(&$result, $dupIds) {
if (in_array($v['customerid'], $dupIds)) {
$parts = array_chunk($v, 2, true);
if (!isset($result[$v['customerid']])) {
$result[$v['customerid']] = $parts[0] + ['new_array' => [$parts[1]]];
} else {
$result[$v['customerid']]['new_array'][] = $parts[1];
}
}
});
print_r(array_values($result));
The output:
Array
(
[0] => Array
(
[customerid] => 13
[customer_fullname] => Chris
[new_array] => Array
(
[0] => Array
(
[profession_id] => 8
[profession_name] => Producer
)
[1] => Array
(
[profession_id] => 7
[profession_name] => Camera
)
)
)
)
Quick hack, maybe there is a nicer solution.
Note: The second "for each" loop is only needed if there is the possibility that the arrays don't have the same fields.
function merge($array1, $array2){
$result = array();
foreach($array1 as $key => $value){
if(isset($array2[$key]) && $array2[$key]!=$array1[$key]){
$result[$key][]=$value;
$result[$key][]=$array2[$key];
}else{
$result[$key]=$value;
}
}
foreach($array2 as $key => $value){
if(!isset($result[$key])){
$result[$key] = $value;
}
}
return $result;
}
print_r(merge($array1, $array2));
I have 2 array's, first array have for example ItemID of my item, second array have description about my item. I want to match data into 1 array.
It looks like:
[rgInventory] => Array
(
[1234567890] => Array
(
[id] => 1234567890
[classid] => 123456789
[instanceid] => 987654321
[amount] => 1
[pos] => 1
)
)
[rgDescriptions] => Array
(
[192837465_918273645] => Array
(
[appid] => 730
[name] => Something
)
)
Items in arrays don't have the same value like ID, but they are in the same order so:
Description for the first item in rgInventory is in the first array inside rgDescriptions.
What should I do to match for example id from rgInventory with name from rgDescriptions in the same array for example $backpack = array();?
Regards for you.
Try this:
<?php
$array1 = array('rgInventory' =>
array(
'1234567890' => array(
'id' => 1234567890,
'classid' => 123456789,
'instanceid' => 987654321,
'amount' => 1,
'pos' => 1
)
)
);
$array2 = array(
'rgDescriptions' => array(
'192837465_918273645' => array(
'appid' => 730, 'name' => 'Something')
)
);
Create new function to combine the two arrays into one array:
function array_sum_recursive($data1, $data2) {
if (!is_array($data1) && !is_array($data2)) {
return $data1 + $data2;
}
// deepest array gets precedence
if (!is_array($data2)) {
return $data1;
}
if (!is_array($data1)) {
return $data2;
}
//merge and remove duplicates
$keys = array_unique(array_merge(array_keys($data1), array_keys($data2)));
foreach ($keys as $key) {
if (isset($data1[$key]) && isset($data2[$key])) {
$result[$key] = array_sum_recursive($data1[$key], $data2[$key]);
} else if (isset($data1[$key])) {
$result[$key] = $data1[$key];
} else {
$result[$key] = $data2[$key];
}
}
if(empty($result)){
echo "no result";
die();
}else{
return $result;
}
}
Put the two array in one array $newarray:
$newonearray = array_sum_recursive($array1, $array2);
echo '<pre>';
print_r($newonearray);
?>
And you will get this:
Array
(
[rgInventory] => Array
(
[1234567890] => Array
(
[id] => 1234567890
[classid] => 123456789
[instanceid] => 987654321
[amount] => 1
[pos] => 1
)
)
[rgDescriptions] => Array
(
[192837465_918273645] => Array
(
[appid] => 730
[name] => Something
)
)
)
Hope this may help.
You can use function each to get each element of both arrays, then merge its with array_merge and save this new item to backup array.
Try something like this
<?php
$rgInventory = ['firstInv' => ['invId' => 1], 'secondInv' => ['invId' => 2]];
$rgDescriptions = ['firstDesc' => ['descId' => 1], 'secondDesc' => ['descId' => 2]];
if (count($rgInventory) && count($rgInventory) == count($rgDescriptions)) {
$backpack = [];
while($inventory = each($rgInventory)) {
$description = each($rgDescriptions);
$item = array_merge($inventory['value'], $description['value']);
$backpack[] = $item;
}
var_dump($backpack);
}
Output will be:
array(2) {
[0]=>
array(2) {
["invId"]=>
int(1)
["descId"]=>
int(1)
}
[1]=>
array(2) {
["invId"]=>
int(2)
["descId"]=>
int(2)
}
}
I have an array within an array like this:
Array
(
[0] => Array
(
[name] => B
[id] => 924572
)
[1] => Array
(
[name] => A
[id] => 120689
)
[2] => Array
(
[name] => A
[id] => 120689
)
[3] => Array
(
[name] => C
[id] => 919644
)
[4] => Array
(
[name] => A
[id] => 120689
)
[5] => Array
(
[name] => B
[id] => 924572
)
)
How can I get the most repeated value from object named name and id?
I've already tried the code below but I'm getting an error: Warning: array_count_values(): Can only count STRING and INTEGER values!
$count = array_count_values($info);
arsort($count);
$popular = array_keys($count);
echo $popular[0];
Any fix regarding to this problem?
"Serializing way" for searching most repeated couples (name,id):
$out = array();
foreach($arr as $el){
$key = serialize($el);
if (!isset($out[$key]))
$out[$key]=1;
else
$out[$key]++;
}
arsort($out);
foreach($out as $el=>$count){
$item = unserialize($el);
echo "Name = ".$item['name'].' ID = '.$item['id'].' Count = '.$count.'<br/>';
}
Output:
Name = A ID = 120689 Count = 3
Name = B ID = 924572 Count = 2
Name = C ID = 919644 Count = 1
update Without loop
.....
arsort($out);
$most = unserialize(key($out));
$most_count = array_shift($out);
echo $most['name'];
echo $most['id'];
echo $most_count;
Output:
A
120689
3
A more linear solution.
$arr = Array
(
Array
(
"name" => "B",
"id" => 924572
),
Array
(
"name" => "A",
"id" => 120689
),
Array
(
"name" => "A" ,
"id" => 120689
),
Array
(
"name" => "C",
"id" => 919644
),
Array
(
"name" => "A",
"id" => 120689
),
Array
(
"name" => "B",
"id" => 924572
));
$countArr = Array();
for($i = 0; $i < count($arr); $i++)
{
$tmpArr = $arr[$i];
if(array_key_exists($tmpArr["name"],$countArr))
$countArr[$tmpArr["name"]]++;
else
$countArr[$tmpArr["name"]] = 0;
}
arsort($countArr);
var_dump($countArr);
Maybe you can work with this solution:
<?php
$info = array(
array(
"name" => "B",
"id" => 924572
),
array(
"name" => "A",
"id" => 120689
),
array(
"name" => "A",
"id" => 120689
),
array(
"name" => "C",
"id" => 919644
),
array(
"name" => "A",
"id" => 120689
),
array(
"name" => "B",
"id" => 924572
),
);
$result = array();
foreach ($info as $infoKey => $infoValue) {
foreach ($infoValue as $itemKey => $itemValue) {
if ($itemKey != "name") {
continue;
}
if (array_key_exists($itemValue, $result)){
$result[$itemValue]++;
continue;
}
$result[$itemValue] = 1;
}
}
arsort($result);
var_dump($result);
Will result in:
array (size=3)
'A' => int 3
'B' => int 2
'C' => int 1
Based on finding the mode and mapping in PHP. Would this work?
$name_array = array_map(function($x) {return $x["name"];}, $info);
$count = array_count_values($name_array);
$mode = array_keys($count, max($count));
To return an array of "name", "id" pairs use:
$return_value = array_filter($info, function($x) use ($mode) { return (in_array($x["name"], $mode));});
Makes use of array_column (requires PHP 5.5 or shim).
$count_values = array_count_values(array_column($array, 'name'));
$most_frequent_name = array_search(max($count_values), $count_values);
Then if you want all arrays with this name:
$items = array_filter($array, function ($v) use ($most_frequent_name) {
return $v['name'] == $most_frequent_name;
});
If several names may have the same top frequency:
$count_values = array_count_values(array_column($array, 'name'));
$most_frequent_names = array_keys($count_values, max($count_values));
$items = array_filter($array, function ($v) use ($most_frequent_names) {
return in_array($v['name'], $most_frequent_names);
});
Try following code. It will give you count of occurrences of all elements
function array_icount_values($arr,$lower=true) {
$arr2=array();
if(!is_array($arr['0'])){$arr=array($arr);}
foreach($arr as $k=> $v){
foreach($v as $v2){
if($lower==true) {$v2=strtolower($v2);}
if(!isset($arr2[$v2])){
$arr2[$v2]=1;
}else{
$arr2[$v2]++;
}
}
}
return $arr2;
}
$arr = array_icount_values($array);
echo "<pre>";
print_r($arr);
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