replace specific array value with another array values in php - php

my 1st array values are
Array (
[0] => abc
[1] => xyz
[2] => Other
[3] => Other
[4] => pqr )
when array contains value as Other i want to replace that with below array
Array (
[0] => lmnsa
[1] => asda )
I want to do this in PHP. any help guys?

First loop over the array1 and test for the value 'Other', if found replace the value with your array2
Note the use of &$a to make the $a from the foreach loop a reference, so that it can be used to replace the original array occurance and not a copy of the array which woudl have been the result without the use of the &
$array1 = Array ( "abc","xyz","Other", "Other", "pqr" );
$array2 = Array ( "lmnsa", "asda" );
foreach ($array1 as &$a) {
if ( $a == 'Other') {
$a = $array2;
}
}
print_r($array1);
The RESULT
Array
(
[0] => abc
[1] => xyz
[2] => Array
(
[0] => lmnsa
[1] => asda
)
[3] => Array
(
[0] => lmnsa
[1] => asda
)
[4] => pqr
)

I don't really understand what result are you looking for.
If you want to just replace elements with value 'Other' with some different value:
$newValue = 'New value instead of Other';
// $newValue = ['abc' 'def']; <-- if you want to replace string by an array. It wasn't unclear what you expect to achieve from the question.
$array = ['a', 'b', 'Other', 'c', 'Other', 'd'];
foreach ($array as $idx => $element) {
if ($element === 'Other') {
$array[$idx] = $newValue;
}
}
Or if you have an array of replacements, which must gradually replace all 'Other' values:
$array = ['a', 'b', 'Other', 'c', 'Other', 'd'];
$replacements = ['New Value 1', 'New Value 2'];
$replacementIdx = 0;
foreach ($array as $idx => $element) {
// Always check if you were not run out of replacement values
if (!isset($replacements[$replacementIdx])) {
break;
}
if ($element === 'Other') {
$array[$idx] = $replacements[$replacementIdx++];
}
}
Instead of using foreach ($array as $key => $value) you may also try to replace elements by reference (see RiggsFolly answer)

Based on your request what Yamingue stated is correct. You may need to clarify what you want. Are you attempting to say if the indexed value of the array initial array is 2 and its value is "Other" to replace it with it with the equivalent value of another array with the same index number?
Its been a while since ive done php buy lets give this a go.
$array1 = Array (
0 => "abc"
1 => "xyz"
2 => "Other"
3 => "Other"
4 => "pqr" );
$array2 = Array (
0 => "lmnsa"
1 => "asda"
2 => "thg"
3 => "ris"
4 => "slrn");
Foreach($array1 as $arr1key => $arr1val) {
If($arr1val == "Other"){
$array1[$arr1key] = $array2[$arr1key];
}
}
You may need to unset the values however as i said been a while for me. Nowbif you want to embed the 2nd array into the value of the first array where it currently says other thats another story, each language is a little different on multidimensional and nested arrays so i cant speak to it.

there are several ways to do it as needed. the first is to replace it with another array like this
`
$array1 = Array (
0 => "abc"
1 => "xyz"
2 => "Other"
3 => "Other"
4 => "pqr" );
$array2 = Array (
0 => "lmnsa"
1 => "asda" );
$array1 = $array2
`

Related

Removing duplicates from array + json, problem with array_unique

I have array something like:
Array (
[0]=>{"a":"b", "c":"d", "h":"e"}
[1]=>{"a":"b", "f":"g"}
)
How i can removing duplicates here? I'm trying array_unique, but it's not working.
Expected result:
Array (
[0]=>{"a":"b", "c":"d", "h":"e"}
[1]=>{"f":"g"}
)
In this scenario, you need to be careful with duplicate keys yet different values. So match to remove duplicates has to be on combination of both key and value.
To do this, we can collect all keys in an array say $map and have all values visited for this keys inside that key array.
Now, we can just do an in_array check to get hold of whether we got some key-value pair like this before or not.
Snippet:
$arr = [
[
'a' => 'b',
'c' => 'd',
'h' => 'e'
],
[
'a' => 'b',
'f' => 'g',
'c' => 'f'
],
[
'a' => 'd',
'c' => 'd'
]
];
$map = [];
foreach($arr as $index => $data){
foreach($data as $key => $value){
if(!isset($map[$key])) $map[$key] = [];
if(in_array($value,$map[$key])) unset($arr[$index][$key]);
else $map[$key][] = $value;
}
}
print_r($arr);
Demo: https://3v4l.org/RWcMu
You can do it with array_diff() and unset() functions. But, you need to decode this JSON values firstly:
foreach($ar as $in => &$js){
$ar[$in] = json_decode($js,true);
}
After this $ar has a view like:
Array
(
[0] => Array
(
[a] => b
[c] => d
[h] => e
)
[1] => Array
(
[a] => b
[f] => g
)
)
Here you can apply array_diff() function:
$diff = array_diff($ar[1],array_diff($ar[1],$ar[0]));
It will collect duplicates from [1] index in [0]:
Array
(
[a] => b
)
Now you can unset these values from [1] index:
foreach($diff as $ind=>$uns){
unset($ar[1][$ind]);
}
And finally you can change JSON view back:
foreach($ar as $in=>&$js){
$ar[$in] = json_encode($js);
}
Result would be:
Array
(
[0] => {"a":"b","c":"d","h":"e"}
[1] => {"f":"g"}
)
Demo
If input elements are objects, then use this loop at the first step:
foreach($ar as $in=>&$obj){
$ar[$in] = (array)$obj;
}
Demo

Merging 2 arrays keeping values from both

I'm trying to merge to arrays using array_merge however I'm either not doing it right or this function doesn't do what I'm expecting.
Here I have 2 arrays
array_merge($array[0], $array[1]);
Array
(
[0] => Array
(
[apples] => 1
[pears] =>
[oranges] =>
[grapes] =>
[melons] => 1
)
[1] => Array
(
[apples] =>
[pears] => 1
[oranges] => 1
[grapes] =>
[melons] =>
[pineapples] =>
[bananas] =>
[lemons] =>
)
)
I'm getting this back, which is just seems to be using the second array
Array
(
[apples] =>
[pears] => 1
[oranges] => 1
[grapes] =>
[melons] =>
[pineapples] =>
[bananas] =>
[lemons] =>
)
But my desired outcome is:
Array
(
[0] => Array
(
[apples] => 1
[pears] => 1
[oranges] => 1
[grapes] =>
[melons] => 1
[pineapples] =>
[bananas] =>
[lemons] =>
)
)
Any help with this would be much appreciated.
From the manual:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.
If you want the ones from either that contain values to overwrite empty ones in either, then filter out the empties:
$result = array_merge(array_filter($array[0]), array_filter($array[1]));
However, if both arrays have the same key and they both have a value then this will still result in the second value. Also, this will not keep keys that are empty in both arrays like pineapples so you might need to loop and check what you want to include or not, or possibly:
$result = array_merge(array_merge(array_filter($array[0]), array_filter($array[1])),
array_filter($array[0]),
array_filter($array[1]));
Method I. Use array_walk_recursive
array_walk_recursive($a, function($v, $k) use (&$r){
isset($r[$k]) ? (!$v ? '' : ($r[$k] = $v)) : ($r[$k] = $v);
});
print_r($r);
Working example : https://3v4l.org/UpR2f
Method 2. Iterate using foreach with ternary operator
$r = [];
foreach($a as $k => $v){
foreach($v as $k1 => $v1){
isset($r[$k1]) ? ($v1==1 ? ($r[$k1] = $v1) : '') : ($r[$k1] = $v1);
}
}
Working example :- https://3v4l.org/WXCpd
If you want to keep keys that are empty in both arrays you can loop and merge the arrays by yourself.
You can take first array, that add keys from second array in foreach loop.
$result = $array[0];
foreach ($array[1] as $key => $value) {
if (empty($result[$key])) {
$result[$key] = $value;
}
}
This will keep the values from the first array if there are conflicting keys. If you rather want to keep the values from second array you can do following.
$result = $array[0];
foreach ($array[1] as $key => $value) {
$result[$key] = $value;
}

How to combine 2 array into 1 array using foreach with different key

I had 2 array with different number of key
First array:
0 =>
array (size=2)
'a' => 1
'b' => 'b'
1 =>
array (size=2)
'a' => 2
'b' => '2b'
Second array:
0 =>
array (size=2)
'a' => 1
'c' => 'c'
The 'a' is act like id but there is problem on 'b' and 'c' are not mandatory to list out.
I tried array_merge before but it quite complex for my next step so i want to know is there others solution for this?
I also tried the foreach loop but it stuck at:
foreach($first_array as $data){
$result[] = $data;
......
}
The output should like this form:
[0] => Array
(
[a] => 1,
[b] => 'b',
[c] => 'c',
)
[1] => Array
(
[a] => 2,
[b] => '2b',
)
If 'a' contains the id of the record, it would be a good idea to use this as an identifier in the result array.
$results = [];
$dataSets = [$first_array, $second_array];
foreach ($dataSets as $dataSet) {
foreach ($dataSet as $record) {
if (!isset($results[$record['a']]) {
// first occurence of this record
$results[$record['a']] = $record;
continue;
}
// next occurence of this record, merge it with existing data
$results[$record['a']] = array_merge($results[$record['a']], $record);
}
}
If the results should be a normal array (e.g. if you want to encode it to JSON and don't want an object), you'll still need to remove the ids at the end
$results = array_values($results);
It is better to use a multi-dimensional array.
For example:
$myarray = array(
array("1", "b", "c"),
array("2", "2b")
);

Combine two different dimensional arrays PHP

I have two different dimensional arrays.
Array 1:
Array1
(
[0] => Array
(
[id] => 123
[price] => 5
[purchase_time] => 2014/4/10
)
[1] => Array
(
[id] => 123
[price] => 5
[purchase_time] => 2014/5/17
)
)
Array 2:
Array2
(
[0] => 5
[1] => 8
)
I want something like this:
Array
(
[0] => Array
(
[id] => 123
[price] => 5
[purchase_time] => 2014/4/10
[Qty] => 5
)
[1] => Array
(
[id] => 123
[price] => 5
[purchase_time] => 2014/5/17
[Qty] => 8
)
)
Basically the first array is the information I got from a SQL table. The second array contains the quantity for the products sold. I now want to combine these two array together and use the combined array to create a new table. Since these two arrays have different dimensions. I'm not sure how to do it. Here is my try:
$i = 0;
foreach($array1 as $row)
{
$newarray = array_merge($row,$array2[$i]);
$i++;
}
Might be a simpler way, but for fun without foreach:
array_walk($array1, function(&$v, $k, $a){ $v['Qty'] = $a[$k]; }, $array2);
The simplest way is:
$i = 0;
foreach($array1 as &$row) {
$row['Qty'] = $array2[$i++];
}
Or if keys of both arrays are the same (0,1,2...) and array have the same length:
foreach($array1 as $k => &$row) {
$row['Qty'] = $array2[$k];
}
If the $array1 and $array2 are mapped by the same indexes, so they have same length, you can try:
foreach($array2 as $index=>$quantity){
$array1[$index]['Qty'] = $quantity;
}
And it´s done!
If you want to keep the original $array1 untouched, you can make a copy before the foreach.
Create new array and store it there. You can access the value of $array2 because they have the same index of $array1 so you can use the $key of these two arrays.
$array3 = [];
foreach($array1 as $key => $val) {
$array3[] = [
'id' => $val['id'],
'price' => $val['price'],
'purchase_time' => $val['purchase_time'],
'Qty' => $array2[$key]
];
}
print_r($array3);

Count instances of value/key in merged arrays and set value by count

I am looking at trying to do an array_merge with these arrays but I need to be able to count how many times a particular value in the array appears and give me that data back.
Here are the original arrays
Array
(
[0] => this
[1] => that
)
Array
(
[0] => this
[1] => that
[2] => some
)
Array
(
[0] => some
[1] => hello
)
Ultimately I would like it to look like this
Array
(
[this] => 2
[that] => 2
[some] => 2
[hello] = > 1
)
That would ultimately allow me to get the key and value I need. I tried 'array_unique` in this process but realized that I may not be able to count the instances of each array that they appear since this would just simple remove them all but one.
I tried something list this
$newArray = array_count_values($mergedArray);
foreach ($newArray as $key => $value) {
echo "$key - <strong>$value</strong> <br />";
}
but I am getting results like this
Array
(
[this] => 2
[that] => 2
[some] => 2
[hello] = > 1
[this] => 3
[that] => 3
[some] => 3
[hello] = > 2
[this] => 2
[that] => 2
[some] => 2
[hello] = > 1
)
Use array_count_values():
$a1 = array(0 => 'this', 1 => 'that');
$a2 = array(0 => 'this', 1 => 'that', 2 => 'some');
$a3 = array(0 => 'some', 1 => 'hello');
// Merge arrays
$test = array_merge($a1,$a2,$a3);
// Run native function
$check = array_count_values($test);
echo '<pre>';
print_r($check);
echo '</pre>';
Gives you:
Array
(
[this] => 2
[that] => 2
[some] => 2
[hello] => 1
)
EDIT: As noted by AlpineCoder:
"This will work only in the case of input arrays using numeric (or unique) keys (since array_merge will overwrite values for the same non-integer key)."
$res = array();
foreach ($arrays as $array) {
foreach ($array as $val) {
if (isset($res[$val])) {
$res[$val]++;
} else {
$res[$val] = 1;
}
}
}
As tyteen4a03 mentioned, use nested foreach loops:
$arr1 = array('foo', 'bar');
$arr2 = array('foo', 'bar', 'baz');
$arr3 = array('baz', 'bus');
$result = array();
foreach(array($arr1, $arr2, $arr3) as $arr) {
foreach ($arr as $value) {
if (!isset($result[$value])) {
$result[$value] = 0;
}
++$result[$value];
}
}
print_r($result);
The outer foreach goes through each set of items (i.e. each array) and the inner foreach loop goes through each item in each set. If the item isn't in the $result array yet, create the key there.
Result:
Array
(
[foo] => 2
[bar] => 2
[baz] => 2
[bus] => 1
)

Categories