How to merge selected elements of an array in PHP? - php

I have an array as
$array = array (
0 => array( 'name' => 'zero'),
1 => array( 'name' => 'one'),
2 => array( 'name' => 'two'),
3 => array( 'name' => 'three'),
4 => array( 'name' => 'four'),
5 => array( 'name' => 'five'),
6 => array( 'name' => 'six'),
);
and I need to merge some elements according to a pattern
$pattern = array(
array('from'=>1, 'to'=>2, 'note'=>'something'),
array('from'=>3, 'to'=>5, 'note'=>'something'),
array('from'=>6, 'to'=>6, 'note'=>'something'),
);
How can I merge the elements to get an array of
$ result = array(
['0'] => array('name'=>'zero'),
['1,2'] => array('name'=>'one+two', 'note'=>'something'),
['3,4,5'] => array('name'=>'three+four+five', 'note'=>'something'),
['6'] => array('name'=>'six', 'note'=>'something'),
);
I understand that I should iterate one array in a loop and check the other one for the corresponding element to create a new array, but which one should I iterate?

If the array keys aren’t actually important, then I’d go about it like this:
$result = $processed = [];
foreach($pattern as $p) { // loop over the patterns
$temp = [];
for($i = $p['from']; $i <= $p['to']; ++$i) { // loop over from -> to
$temp[] = $array[$i]['name']; // collect names of those items
$processed[] = $i; // store index of item as an already processed one
}
$result[] = ['name' => implode('+', $temp), 'note' => $p['note']];
}
$temp = [];
foreach($array as $key => $item) {
if(!in_array($key, $processed)) { // if index is not in list of already processed items
$temp[] = $item['name'];
}
}
array_unshift($result, ['name' => implode('+', $temp)]); // add to front of result
That will get you a result of the form
Array
(
[0] => Array
(
[name] => zero
)
[1] => Array
(
[name] => one+two
[note] => something
)
[2] => Array
(
[name] => three+four+five
[note] => something
)
[3] => Array
(
[name] => six
[note] => something
)
)

Related

how to explode array in php

i have data array, and this my array
Array
(
[0] => Array
(
[id] => 9,5
[item] => Item A, Item B
)
[1] => Array
(
[id] => 3
[item] => Item C
)
)
in array 0 there are two ID which I separated using a comma, I want to extract the data into a new array, how to solve this?
so the output is like this
Array
(
[0] => Array
(
[id] => 9
[item] => Item A
)
[1] => Array
(
[id] => 3
[item] => Item C
)
[2] => Array //new array
(
[id] => 5
[item] => Item B
)
)
this my code
$arr=array();
foreach($myarray as $val){
$arr[] = array(
'id' => $val['id'],
'item' => $val['item'],
);
}
echo '<pre>', print_r($arr);
$arr = [
array(
'id' => '9,5',
'item' => 'Item A, Item B'
),
array(
'id' => 3,
'item' => 'Item C'
)
];
$newArr = array_reduce($arr, function($tmp, $ele){
$arrIds = explode(',', $ele['id']);
$arrItems = explode(',', $ele['item']);
forEach($arrIds as $key => $arrId) {
$tmp[] = array('id' => $arrId, 'item' => $arrItems[$key]);
}
return $tmp;
});
The code down below should do the job. But I didn't understand why you didn't create those items seperately in the first place.
foreach ($arr as $i => $data) {
if (!str_contains($data['id'], ',')) continue;
$items = explode(',', $data['item']);
foreach(explode(',', $data['id']) as $i => $id) {
$new = ['id' => $ids[$i], 'item' => $items[$i]];
if ($i) $arr[] = $new;
else $arr[$i] = $new;
}
}

PHP : Concatenate arrays with condition

I'm trying to read a session variable, create arrays and concatenate them :
Session variable sample:
Array
(
[0] => Array
(
[idArticle] => 224
[ntypeArticle] => 1
)
[1] => Array
(
[idArticle] => 556
[ntypeArticle] => 2
)
[2] => Array
(
[idArticle] => 312
[ntypeArticle] => 1
)
)
I need to read this arrays one by one and create arrays by "ntypeArticle".
If ntypeArticle=1, create array1
If ntypeArticle=2, create array2
My code :
$type1 = array();
$type2= array();
$typeAll = array();
foreach($_SESSION['cart'] as $item)
{
if ($item['ntypeArticle'] == 1) {
$type1= array ( "Type" => '1', );
} else {
$type2= array ( "Type" => '2', );
}
array_push($typeAll , $type1 , $type2);
}
But this creates empty arrays.
Wanted output :
Array
(
[0] => Array
(
[type] => 1
)
[1] => Array
(
[type] => 2
)
[2] => Array
(
[type] => 1
)
)
All you need is this simple thing:
$out = [];
foreach($_SESSION['cart'] as $k => $item)
{
$out[$k] = ['Type' => $item['ntypeArticle']];
}
Now if you output $out variable you get what you need.
Try This
$newOp1 = array()
$newOp2 = array()
foreach($_SESSION['cart'] as $item){
if($item["ntypeArticle"] == 1){
$newOp1[]['type'] = $item["ntypeArticle"]
}else{
$newOp2[]['type'] = $item["ntypeArticle"]
}
}
print_r($newOp1);
print_r($newOp2);
Basing on information you provided, all you want to do is to extract nTypeArticle as type element. That's all.
//array from your example
$inputArray = array(
array(
'idArticle' => 224,
'nTypeArticle' => 1
),
array(
'idArticle' => 556,
'nTypeArticle' => 2
),
array(
'idArticle' => 312,
'nTypeArticle' => 1
),
);
$outputArray = array_map(function($inputElement) {
return array('type' => $inputElement['nTypeArticle']);
}, $inputArray);
var_dump($outputArray);
//Output (the same as yours):
//array (size=3)
// 0 =>
// array (size=1)
// 'type' => int 1
// 1 =>
// array (size=1)
// 'type' => int 2
// 2 =>
// array (size=1)
// 'type' => int 1
$output = new array();
$input = array(
array(
"idArticle" => 224,
"nTypeArticle" => 1
),
array(
"idArticle" => 556,
"nTypeArticle" => 2
),
array(
"idArticle" => 312,
"nTypeArticle" => 1
)
);
foreach($input as $article) {
array_push($output, new array("type"=>$article["nTypeArticle"]));
}
print_r($output);
This gives you the thing you asked for.
(Code has been not tested)

Add array elements to associative array

I am unable to find a way to take the elements of an array (product IDs) and add them to a particular key of an associative array ($choices['id]) so that it creates as many instances of that array ($choices[ ]) as there are elements in $id.
I want the final version of $choices[ ] to include as many arrays as there are elements in $id[ ].
After that I want to repeat this process for part_numbers & quantity.
// Create $choices array with keys only
$choices = array(
'id' => '',
'part_number' => '',
'quantity' => '',
);
// Insert $id array values into 'id' key of $choices[]
$id = array('181', '33', '34');
If I'm understanding your question correctly, you mean something like this?
$choices = array();
$id = array('181', '33', '34');
foreach($id as $element)
{
$choices[] = array(
'id' => $element,
'part_number' => '',
'quantity' => '',
);
}
echo "<pre>";
print_r($choices);
echo "</pre>";
Output:
Array (
[0] => Array
(
[id] => 181
[part_number] =>
[quantity] =>
)
[1] => Array
(
[id] => 33
[part_number] =>
[quantity] =>
)
[2] => Array
(
[id] => 34
[part_number] =>
[quantity] =>
)
)
Edit:
A more general solution would be as follows:
$choices = array();
$values = array('sku-123', 'sku-132', 'sku-1323');
foreach($values as $i => $value){
if(array_key_exists($i, $choices))
{
$choices[$i]['part_number'] = $value;
}
else
{
$choices[] = array(
'id' => '',
'part_number' => $value,
'quantity' => '',
);
}
}
This can be used for array creation and insertion, hence the if/else block.

PHP array combining every other element

I have an object with several properties that creates a multi dimensional array. I'm trying to figure out how to create a new array that combines two seperate objects into one. It would go from this:
array(
object_1(
'id' => '1',
'name' => 'joe'
etc....),
object_2(
'id' => '2',
'name' => 'jessica',
etc....)
object_3(
'id' => '3',
'name' => 'tim',
etc....)
object_4(
'id' => '4',
'name' => 'tammy',
etc....)
);
And become:
array(
object_1(
'id' => '1',
'name' => 'joe',
etc...
'id2' = > '2',
'name2' => 'jessica',
etc...)
object_2(
'id' => '3',
'name' => 'tim',
etc...
'id2' = > '4',
'name2' => 'tammy',
etc...)
So, I need to combine the data from alternating elements, and also change the key in all the second objects so it doesn't match the first. Make sense? Sorry if it doesn't, I'll try to clarify if you need!
Thanks for any help....
EDIT: first two stdclass objects according to print_r:
[results] => Array
(
[0] => stdClass Object
(
[email] => sample#info.com
[message] => Create another test
[image] => 138.png
[fid] => 53
)
[1] => stdClass Object
(
[email] => info#sample.com
[message] => none
[image] => 330.jpg
[fid] => 52
)
and I want it to become:
[results] => Array
(
[0] => stdClass Object
(
[email] => sample#info.com
[message] => Create another test
[image] => 138.png
[fid] => 53
[email2] => info#sample.com
[message2] => none
[image2] => 330.jpg
[fid2] => 52
)
Does that clarify?
Assuming it's actually a multi-dimensional array, not an array of objects, this should do it:
$new_array = array();
for ($i = 0; $i < count($array); $i +=2) {
$new_array[] = $array[$i];
foreach ($array[$i+1] as $key => $value) {
$new_array[$i/2][$key.'2'] = $value;
}
}
EDIT: For an array of objects, it becomes:
$new_array = array();
for ($i = 0; $i < count($array); $i +=2) {
$new_array[] = $array[$i];
foreach (get_object_vars($array[$i+1] as $key => $value) {
$new_array[$i/2]->{$key.'2'} = $value;
}
}
This will only work for public properties.
You could do something like
for($i=0;$i<count($array);$i+=2) {
$id = $array[$i]['id'];
$name = $array[$i]['name'];
$id2 = $array[$i+1]['id'];
$name2 = $array[$i+1]['name'];
}
or
$newarray = array();
$j=0;
for($i=0;$i<count($array);$i+=2) {
$newarray[$j]['id'] = $array[$i]['id'];
$newarray[$j]['nae'] = $array[$i]['name'];
$newarray[$j]['id2'] = $array[$i+1]['id'];
$newarray[$j]['name2'] = $array[$i+1]['name'];
$j++;
}

Which PHP Array function should I use?

I have two arrays:
Array
(
[0] => Array
(
[id] => 1
[type] => field
[remote_name] => Title
[my_name] => title
[default_value] => http%3A%2F%2Ftest.com
)
[1] => Array
(
[id] => 2
[type] => field
[remote_name] => BookType
[my_name] => book-type
[default_value] =>
)
[2] => Array
(
[id] => 3
[type] => value
[remote_name] => dvd-disc
[my_name] => dvd
[default_value] =>
)
)
Array
(
[title] => Test
[book-type] => dvd
)
I need to take each key in the second array, match it with the my_name value in the first array and replace it with the corresponding remote_name value of the first array while preserving the value of the second array.
There's got to be some carrayzy function to help!
EDIT: There will also be a few cases that the value of the second array will need to be replaced by the value of the first array's remote_name where the value of the second array matches the value of the first array's my_name. How can I achieve this?
EG: book-type => dvd should turn into BookType => dvd-disc
Like so?:
$first = array(
array(
'id' => 1,
'type' => 'field',
'remote_name' => 'Title',
'my_name' => 'title',
'default_value' => 'http%3A%2F%2Ftest.com',
),
array(
'id' => 2,
'type' => 'field',
'remote_name' => 'BookType',
'my_name' => 'book-type',
'default_value' => '',
),
array(
'id' => 3,
'type' => 'value',
'remote_name' => 'dvd-disc',
'my_name' => 'dvd',
'default_value' => '',
),
);
$second = array(
'title' => 'Test',
'book-type' => 'dvd',
);
$map = array('fields' => array(), 'values' => array());
foreach ($first as $entry) {
switch ($entry['type']) {
case 'field':
$map['fields'][$entry['my_name']] = $entry['remote_name'];
break;
case 'value':
$map['values'][$entry['my_name']] = $entry['remote_name'];
break;
}
}
$new = array();
foreach ($second as $key => $val) {
$new[isset($map['fields'][$key]) ? $map['fields'][$key] : $key] = isset($map['values'][$val]) ? $map['values'][$val] : $val;
}
print_r($new);
Output:
Array
(
[Title] => Test
[BookType] => dvd-disc
)
Explanation:
The first loop collects the my_name/remote_name pairs for fields and values and makes them more accessible.
Like so:
Array
(
[fields] => Array
(
[title] => Title
[book-type] => BookType
)
[values] => Array
(
[dvd] => dvd-disc
)
)
The second loop will traverse $second and use the key/value pairs therein to populate $new. But while doing so will check for key/value duplicates in $map.
Keys or values not found in the map will be used as is.
foreach($arr1 as &$el) {
$el['remote_name'] = $arr2[$el['my_name']];
}
unset($el);
I am not aware of such a carrayzy function, but I know how you could do it:
//$array1 is first array, $array2 is second array
foreach($array1 as $key => $value){
if (isset($value['remote_name'], $value['my_name']) && $value['remote_name'] && $value['my_name']){
$my_name = $value['my_name'];
if (isset($array2[$my_name])) {
$remote_name = $value['remote_name'];
$array2[$remote_name] = $array2[$my_name];
//cleanup
unset($array2[$my_name]);
}
}
}

Categories