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

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

Related

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

Move array in array to parent array php

Is there a specific function to move array which is in array to the parent array as key or value.
array(5) { [0]=> array(1) { [0]=> string(2) "id" } [1]=> array(1) { [0]=> string(7)
"buydate" } [2]=> array(1) { [0]=> string(6) "expire" } [3]=> array(1) { [0]=> string(6)
"planid" } [4]=> array(1) { [0]=> string(5) "buyer" } }
Result I would like to get is:
array() { [0] => 'id', [1] => 'buydate' etc. }
Or
array('id', 'buydate' etc.. )
Is it possible to achieve without foreach ?
array_map() is extremely powerful and should do the trick:
$array = ... ; // your initial array
$flattened_array = array_map(function($item) {
return $item[0];
}, $array);
If you want to flatten the desired array, and use foreach you can do it this way.
Consider this example:
// Sample data:
$values = array(
0 => array(
0 => 'id',
),
1 => array(
0 => 'buydate',
),
2 => array(
0 => 'expire',
),
3 => array(
0 => 'planid',
),
4 => array(
0 => 'buyer',
),
);
$new_values = array();
foreach($values as $key => $value) {
$new_values[] = $value[0];
}
print_r($new_values);
Sample Output:
Array
(
[0] => id
[1] => buydate
[2] => expire
[3] => planid
[4] => buyer
)
Or alternatively, you can you the iterator. Consider this example:
$new_values = array();
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($values));
foreach($iterator as $value) {
$new_values[] = $value;
}
It should gave you the same output.

Remove similar objects from array?

I have an array of objects, but I need to remove a similar objects by a few properties from them:
for example:
array(12) {
[0]=>
object(stdClass)#848 (5) {
["variant"]=>
object(stdClass)#849 (4) {
["name"]=>
string(8) "Alex"
}
["age"]=>
int(10)
}
[1]=>
object(stdClass)#851 (5) {
["variant"]=>
object(stdClass)#852 (4) {
["name"]=>
string(8) "Alex"
}
["age"]=>
int(10)
}
How to make a one object in array for this ( if for example I need to compare only by a name property? )
Still have an issue with it.
Updated
I've create a new array of objects:
$objects = array(
(object)array('name'=>'Stiven','age'=>25,'variant'=>(object)array('surname'=>'Sigal')),
(object)array('name'=>'Michael','age'=>30,'variant'=>(object)array('surname'=>'Jackson')),
(object)array('name'=>'Brad','age'=>35,'variant'=>(object)array('surname'=>'Pit')),
(object)array('name'=>'Jolie','age'=>35,'variant'=>(object)array('surname'=>'Pit')),
);
echo "<pre>";
print_r($objects);
So what I need to do is to compare an object properties (variant->surnames and ages), if two objects has a similar age and variant->surname we need to remove the one of these objects.
A half of solution is:
$tmp = array();
foreach ($objects as $item=>$object)
{
$tmp[$object->variant->surname][$object->age] = $object;
}
print_r($tmp);
Unfortunatelly I need an old-style array of objects.
I've found an example.
<?php
$a = array (
0 => array ( 'value' => 'America', ),
1 => array ( 'value' => 'England', ),
2 => array ( 'value' => 'Australia', ),
3 => array ( 'value' => 'America', ),
4 => array ( 'value' => 'England', ),
5 => array ( 'value' => 'Canada', ),
);
$tmp = array ();
foreach ($a as $row)
if (!in_array($row,$tmp)) array_push($tmp,$row);
print_r ($tmp);
?>
Quoted from here

Search key replace value

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
)

Categories