Search key replace value - php

Let's say I have an array:
$myArray = array('alfa' => 'apple', 'bravo' => 'banana', 'charlie' => 'cherry', 'delta' => 'danjou pear');
I want to search it for certain keys and if found replace the values of those according to this other array:
$myReplacements = array('bravo' => 'bolognese', 'lie' => 'candy');
I know I can do this:
function array_search_replace($haystack, $replacements, $exactMatch = false) {
foreach($haystack as $haystackKey => $haystackValue) {
foreach($replacements as $replacementKey => $replacementValue) {
if($haystackKey == $replacementKey || (!$exactMatch && strpos($haystackKey, $replacementKey) !== false)) {
$haystack[$haystackKey] = $replacementValue;
}
}
}
return $haystack;
}
But, is there really no smarter/faster way to do it?
EDIT: I also need to be able to search for keyparts, so that 'lie' and 'charlie' results in a match.
EDIT2: Expected results are:
var_dump(array_search_replace($myArray, $myReplacements));
array(4) { ["alfa"]=> string(5) "apple" ["bravo"]=> string(9) "bolognese" ["charlie"]=> string(5) "candy" ["delta"]=> string(11) "danjou pear" }
var_dump(array_search_replace($myArray, $myReplacements, true));
array(4) { ["alfa"]=> string(5) "apple" ["bravo"]=> string(9) "bolognese" ["charlie"]=> string(6) "cherry" ["delta"]=> string(11) "danjou pear" }

You can use the PHP's array_replace function.
Also, array_merge does something similar.
In your code:
$finalArray = array_replace($myArray, $myReplacements);
Full PHP Code
<?php
$myArray = array('alfa' => 'apple', 'bravo' => 'banana', 'charlie' => 'cherry', 'delta' => 'danjou pear');
$myReplacements = array('bravo' => 'bolognese', 'lie' => 'candy');
$finalArray = array_replace($myArray, $myReplacements);
print_r($finalArray);
?>
Output
Array
(
[alfa] => apple
[bravo] => bolognese
[charlie] => cherry
[delta] => danjou pear
[lie] => candy
)
Fiddle here: http://codepad.viper-7.com/60o5xT

Is this what you need ?
<?php
$myArray = array('alfa' => 'apple', 'bravo' => 'banana', 'charlie' => 'cherry', 'delta' => 'danjou pear');
$myReplacements = array('bravo' => 'bolognese', 'lie' => 'candy');
print_r(array_merge($myArray, $myReplacements));
?>
Output:
Array
(
[alfa] => apple
[bravo] => bolognese
[charlie] => cherry
[delta] => danjou pear
[lie] => candy
)
Using array_merge

Arrays in PHP are hashes, you don't need to search for a key, you can access it in O(1) time.
$myArray = array('alfa' => 'apple', 'bravo' => 'banana', 'charlie' => 'cherry', 'delta' => 'danjou pear');
$myReplacements = array('bravo' => 'bolognese', 'lie' => 'candy');
var_dump($myArray);
foreach($myReplacements as $k => $v) {
if(array_key_exists($k, $myArray)) {
$myArray[$k] = $v;
}
}
var_dump($myArray);
Output:
array(4) {
["alfa"]=>
string(5) "apple"
["bravo"]=>
string(6) "banana"
["charlie"]=>
string(6) "cherry"
["delta"]=>
string(11) "danjou pear"
}
array(4) {
["alfa"]=>
string(5) "apple"
["bravo"]=>
string(9) "bolognese"
["charlie"]=>
string(6) "cherry"
["delta"]=>
string(11) "danjou pear"
}

you can use the following code to directly replace the matching key
<?php
$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");
$basket = array_replace($base, $replacements, $replacements2);
print_r($basket);
?>
output:
Array
(
[0] => grape
[1] => banana
[2] => apple
[3] => raspberry
[4] => cherry
)

Related

combine 2 comma separated list into one in php [duplicate]

This question already has answers here:
How would combine multiple exploded lists created by foreach into one array? [duplicate]
(4 answers)
Closed 7 months ago.
I have 2 arrays that are coming from the database, [options] column has comma-separated values.
Array
(
[0] => Array
(
[id] => 143
[menu_id] => 590
[name] => bread
[options] => small, large
)
[1] => Array
(
[id] => 144
[menu_id] => 590
[name] => jam
[options] => mango, orange, grape
)
)
Is there have any way to combine the list of [options] at [0] and [1]?
Example: small, large, mango, orange, grape
Approach
<?php foreach ($menu_options as $key => $menu_option) : ?>
<?PHP $exploded_variant_options = explode(',', $menu_option['options']);
foreach ($exploded_variant_options as $exploded_variant_option) : ?>
<?php echo ucfirst(sanitize($exploded_variant_option)); ?> //print one by one
<?php endforeach; ?>
<?php endforeach; ?>
My suggestion would be to use array_merge. The code would look like this:
<?php
$all_options = [];
foreach( $menu_options as $key => $menu_option ) {
$all_options = array_merge($all_options, explode(", ", $menu_option["options"]));
}
?>
if this is your array :
$arrays = array (
array( 'id' => 143, 'menu_id' => 590, 'name' => 'bread', 'options' => 'small,large'),
array( 'id' => 144, 'menu_id' => 590, 'name' => 'jam', 'options' => 'mango,orange,grape')
);
you can use array_map for achieving that :
function spliter($key, $value){
if($key == 'options')
return $value = explode(',', $value);
else
return $value;
}
foreach($arrays as &$array)
$array = array_map( 'spliter' , array_keys($array), $array);
then this will be a dump of your $arrays :
array(2) {
[0]=>
array(4) {
[0]=>
int(143)
[1]=>
int(590)
[2]=>
string(5) "bread"
[3]=>
array(2) {
[0]=>
string(5) "small"
[1]=>
string(5) "large"
}
}
[1]=>
&array(4) {
[0]=>
int(144)
[1]=>
int(590)
[2]=>
string(3) "jam"
[3]=>
array(3) {
[0]=>
string(5) "mango"
[1]=>
string(6) "orange"
[2]=>
string(5) "grape"
}
}
}
If you just want to print out all the options (insertion order) and not modify them further, you could also just call this:
<?php
$arr = [
['id' => 143, 'menu_id' => 590, 'name' => 'bread', 'options' => 'small, large'],
['id' => 144, 'menu_id' => 590, 'name' => 'jam', 'options' => 'mango, orange, grape']
];
var_dump(array_reduce(array_column($arr, 'options'), function ($c, $i) {
return $c ? "${c}, ${i}" : $i;
}));
// prints: string(34) "small, large, mango, orange, grape"
?>
Otherwise, I suggest using the approach shown by "Teodor".

Combining indexes in an array PHP

I can't quite seem to grasp how I would go about combining the indexes in this array. Below is an example of the array. Any help, resources, or direction would be appreciated.
$array_one = array(
10 => array(0 => 2/3-AM),
10 => array(0 => AUT-PR),
1195 => array(0 => 1/2-AM),
1258 => array(0 => GR-1),
1195 => array(0 => 1/7-PM),
);
I'd like for it to look like this:
$array_one = array(
10 => array(0 => 2/3-AM, AUT-PR),
1195 => array(0 => 1/2-AM, 1/7-PM),
1258 => array(0 => GR-1),
);
var_dump
Making assumptions from your screenshot, I think you meant your input array is:
$input = array(
array(10 => array(0 => '2/3-AM')),
array(10 => array(0 => 'AUT-PR')),
array(1195 => array(0 => '1/2-AM')),
array(1258 => array(0 => 'GR-1')),
array(1195 => array(0 => '1/7-PM')),
);
To get this into your target format:
$output = [];
foreach ($input as $keys) {
foreach ($keys as $key => $values) {
foreach ($values as $value) {
$output[$key][] = $value;
}
}
}
var_dump($output);
This results in:
array(3) {
[10]=> array(2) {
[0]=> string(6) "2/3-AM"
[1]=> string(6) "AUT-PR"
}
[1195]=> array(2) {
[0]=> string(6) "1/2-AM"
[1]=> string(6) "1/7-PM"
}
[1258]=> array(1) {
[0]=> string(4) "GR-1"
}
}

How to separate elements from an array values on php and built new array?

i've got this array (from a csv file) :
array (
0 => 'entity_id;commission_book;old_price;new_price',
1 => '667;667;667;667',
2 => '668;668;668;668'
)
How to build a new array that looks like :
[0] : (
'entity_id' => '667',
'commission_book' => '667',
'old_price' => '667',
'new_price' => '667',
);
[1] : (
'entity_id' => '668',
'commission_book' => '668',
'old_price' => '668',
'new_price' => '668',
)
In other words, i want to buid 2 objects using the first array, is there any way to perfom that please ? I'm trying for hours now
This is a simply but elegant way to do that:
<?php
$input = [
0 => 'entity_id;commission_book;old_price;new_price',
1 => '667;667;667;667',
2 => '668;668;668;668'
];
$output = [];
// drop header entry
array_shift($input);
// process remaining entries
foreach ($input as $key=>$entry) {
$x = &$output[$key];
list(
$x['entity_id'],
$x['commission_book'],
$x['old_price'],
$x['new_price']
) = explode(';', $entry);
}
print_r($output);
The output of the above is:
Array
(
[0] => Array
(
[new_price] => 667
[old_price] => 667
[commission_book] => 667
[entity_id] => 667
)
[1] => Array
(
[new_price] => 668
[old_price] => 668
[commission_book] => 668
[entity_id] => 668
)
)
Short solution with array_slice and array_combine:
$from_csv = [
0 => 'entity_id;commission_book;old_price;new_price',
1 => '667;667;667;667',
2 => '668;668;668;668'
];
$result = [];
$keys = explode(";", $from_csv[0]); // header fields
foreach(array_slice($from_csv, 1) as $v){
$result[] = array_combine($keys, explode(";", $v));
}
echo '<pre>';
var_dump($result);
// the output:
array(2) {
[0]=>
array(4) {
["entity_id"]=>
string(3) "667"
["commission_book"]=>
string(3) "667"
["old_price"]=>
string(3) "667"
["new_price"]=>
string(3) "667"
}
[1]=>
array(4) {
["entity_id"]=>
string(3) "668"
["commission_book"]=>
string(3) "668"
["old_price"]=>
string(3) "668"
["new_price"]=>
string(3) "668"
}
}
$array = array(
0 => 'entity_id;commission_book;old_price;new_price',
1 => '667;667;667;667',
2 => '668;668;668;668');
$array[0] = explode(";",$array[0]);
$array[1] = explode(";",$array[1]);
$array[2] = explode(";",$array[2]);
$newarray = array();
for ($i=0;$i<count($array[0]);$i++){
$newarray[0][$array[0][$i]] = $array[1][$i];
$newarray[1][$array[0][$i]] = $array[2][$i];
}
echo "<pre>";
var_dump($array);
var_dump($newarray);
echo "</pre>";

How to merge array by taking values from other array in php

I have two arrays like this
$array1 = ['name'=>'john', 'age'=> 10]
$array2 = ['name' => 'johnKaff', 'class' => 'User', 'option'=array('c1', 'c2')]
The result i want is
$array2 = ['name' => 'john', 'class' => 'User', 'option'=array('c1', 'c2'), 'age'=> 10]
The values from $array1 should always override if have same key in $array2
Use array_replace():
$result = array_replace($array2, $array1);
Where:
$array1 - The array in which elements are replaced.
$array2 - The array from which elements will be extracted.
Output:
Array
(
[name] => john
[class] => User
[option] => Array
(
[0] => c1
[1] => c2
)
[age] => 10
)
Use the + operator:
$combined_array = $array1 + $array2;
The array listed first wins when each array has an element with the same key.
Example:
$array1 = array('name'=>'john', 'age'=> 10);
$array2 = array('name' => 'johnKaff', 'class' => 'User', 'option'=>array('c1', 'c2'));
$combined_array = $array1 + $array2;
var_dump($combined_array);
Output:
array(4) {
["name"]=>
string(4) "john"
["age"]=>
int(10)
["class"]=>
string(4) "User"
["option"]=>
array(2) {
[0]=>
string(2) "c1"
[1]=>
string(2) "c2"
}
}
You should use array_merge:
array_merge($array1, $array2);

PHP search multidimensional array for substring

I'm trying to search for a substring within part of the bottom layer of a 2-layer array and return the key from the top layer. E.g. in the array below searching within "A" for "ca" would return "0" and "2" (but would miss "cattle"):
Array (
[0] => Array (
[A] => cat
[B] => horses
)
[1] => Array (
[A] => dog
[B] => cattle
)
[2] => Array (
[A] => cat
[B] => sheep
)
)
You can try like this :
$array = array(
array(
"A" => "cat",
"B" => "horse"
),
array(
"A" => "dog",
"B" => "cattle"
),
array(
"A" => "cat",
"B" => "sheep"
),
);
$result = mySearch($array, "A", "ca");
function mySearch($array, $key, $search)
{
$results = array();
foreach ($array as $rootKey => $data) {
if (array_key_exists($key, $data)) {
if (strncmp($search, substr($data[$key], 0, 2), strlen($search)) == 0) {
$results[] = $rootKey;
}
}
}
return $results;
}
var_dump($result);
Will output :
array(2) {
[0]=>
int(0)
[1]=>
int(2)
}
Note that this method is not encoding safe (you may use mb_str* instead of str* function family, more details here).

Categories