PHP array combining every other element - php

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++;
}

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

How to merge selected elements of an array in 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
)
)

Adding same key and values to associative array php

I have an array like this
Array
(
[0] => Array
(
[catid] => 1
[percentage] => 4
[name] => Access Control
)
[1] => Array
(
[catid] => 7
[percentage] => 1
[name] => Audio Video
)
[2] => Array
(
[catid] => 5
[percentage] => 1
[name] => Home Automation
)
)
tho this array i want to add a pair of catid,percentageand name as another
array on the next key eg:
[3] => Array
(
[catid] => 7
[percentage] => 0
[name] => 'some name'
)
Here is my code
//another array
$id=array('1','2',....n);
//$data is my original array
foreach($id as $key=>$value){
$data[]['catid']=$value;
$data['percentage'][]='0';
$data['name'][]='Some name';
}
But it will give wrong output.
//another array
$id=array('1','2',....n);
$i = count($data);
//$data is my original array
foreach($id as $key=>$value){
$data[$i]['catid']=$value;
$data[$i]['percentage']='0';
$data[$i]['name']='Some name';
$i++;
}
The only thing you need to do is:
$yourArray[] = [
'catid' => 7,
'percentage' => 0,
'name' => 'some name'
];
You're building the array wrong:
This pushes a NEW element onto the main $data array, then assigns a key/value of catid/$value to that new element:
$data[]['catid']=$value;
Then you create a new top-level percentage, and push a zero into it, and ditto for name:
$data['percentage'][]='0';
$data['name'][]='Some name';'
You can't build a multi-key array like this. You need to build a temporary array, then push the whole thing onto the main array:
$temp = array();
$temp['catid'] = $value;
$temp['percentage'] = 0;
$temp['name'] = 'Some name';
$data[] = $temp;
Or in shorthand notation:
$data[] = array('catid' => $value, 'percentage' => 0, 'name' = 'Somename');
You can use array_push
$a1 = array(array('catid' => '1', 'percentage' => '4', 'name' => 'Access Control'));
$a2 = array('catid' => '7', 'percentage' => '0', 'name' => 'Some Name');
array_push($a1 ,$a2);
print_r($a1);

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.

How can I replace a certain part of array using PHP?

Just need a little help here about arrays. Because I am trying to create a code that when you click it it will replace a certain array values.
In the base array suppose that we have this array:
Array(
[0] => Array(
[id] => 1,
[name] => xyz
),
[1] => Array(
[id] => 4,
[name] => fsa
),
)
And in my new array I have something like this
Array(
[id] => 4,
[name] => pop
)
I have a validation like this: In the base array I put this array in $base_array and in my new array I have $update_array
$get_updated_array_id = $update_array[id];
for($x = 0; $x <= sizeof($base_array); $x++){
$target = $base_array[$x]['id'];
if($get_updated_array_id == $target){
//should be replace the array value ID '4'
}
}
So the final result should be:
Array(
[0] => Array(
[id] => 1,
[name] => xyz
),
[1] => Array(
[id] => 4,
[name] => pop
),
)
Any idea how can I do that? Thanks
<?php
$array = array(
array('id' => 2,'name' => 'T'),
array('id' => 4,'name' => 'S')
);
$replace = array('id' => 4,'name' => 'New name');
foreach ($array as $key => &$value) {
if($value['id'] == $replace['id'] ) {
$value = $replace;
}
}
print_r($array);
$new_array = array(
[id] => 4,
[name] => pop
);
$get_updated_array_id = $update_array[id];
for($x = 0; $x <= sizeof($base_array); $x++){
$target = $base_array[$x]['id'];
if($get_updated_array_id == $target){
$base_array[$x] = $new_array;
}
}
//PHP >= 5.3
array_walk($base_array, function (& $target) use ($update_array) {
if ($target['id'] == $update_array['id']) {
$target = $update_array;
}
});

Categories