How can I replace a certain part of array using PHP? - 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;
}
});

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 - Order array associative by specific value

I'm looking for a way to order an array associative by a specific value, I'm not sure if it's possible. I tried it with array_multisort() and usort() functions, but I'm afraid that I can not get it.
Example:
$array[] = array('id' => 74215, 'type' => 'BOX');
$array[] = array('id' => 76123, 'type' => 'UNT');
$array[] = array('id' => 71231, 'type' => '');
$array[] = array('id' => 79765, 'type' => 'UNT');
$array[] = array('id' => 77421, 'type' => 'BOX');
If I want to order by 'BOX', then the array will be:
Array (
[0] => Array
(
[id] => 77421
[type] => 'BOX'
)
[1] => Array
(
[id] => 74215
[type] => 'BOX'
)
[2] => Array
(
[id] => 76123
[type] => 'UNT'
)
.
.
.
I could pass other string like 'UNT', and order by like that.
Is this possible??
I assume you want to "sort" by string match, first all those who match that string, after that all those that don't. Unless you have an archaic php version, this could work:
$sortvalue = 'BOX';
usort($array, function($a, $b) use ($sortvalue) {
if($a['type'] == $sortvalue) return -1;
elseif($b['type'] == $sortvalue) return 1;
else return 0;
});
this should put any 'BOX' entry to the front of your array.
If all others shall be grouped, instead of return 0 do return $a['type'] < $b['type'].
edit: integrated kamal pal's suggestion/correction
I'm not sure if PHP has it's own function that does that, but i write my own, hope it helps:
function sortArray($array_x, $key)
{
$added_indexes;
$new_array;
for($i=0;$i<count($array_x);$i++)
{
if($array_x[$i]['type']==$key){
$new_array[]=$array_x[$i];
$added_indexes[]=$i;
}
}
for($i=0;$i<count($array_x);$i++)
{
if(!in_array($i,$added_indexes))
{
$new_array[]=$array_x[$i];
}
}
return $new_array;
}
So when you do this:
$array[] = array('id' => 74215, 'type' => 'BOX');
$array[] = array('id' => 76123, 'type' => 'UNT');
$array[] = array('id' => 71231, 'type' => '');
$array[] = array('id' => 79765, 'type' => 'UNT');
$array[] = array('id' => 77421, 'type' => 'BOX');
print_r(sortArray($array,"BOX"));
Gives this:
Array
(
[0] => Array
(
[id] => 74215
[type] => BOX
)
[1] => Array
(
[id] => 77421
[type] => BOX
)
[2] => Array
(
[id] => 76123
[type] => UNT
)
[3] => Array
(
[id] => 71231
[type] =>
)
[4] => Array
(
[id] => 79765
[type] => UNT
)
)
Yeah I was thinking in a similar solution:
usort($array, function ($a, $b) {
return $a['type'] == 'BOX' ? -1 : ($b['type'] == 'BOX' ? 1 : 0);
});

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

Sort PHP array by group of 3 keys [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Sort multidimensional array by multiple keys
I am trying to find some way how to sort array by key name, but nothing worked so far. The tricky part for me is to sort array by grouping 3 keys. I have this array.
[0] => Array
(
[id] => 8
[zbo_data] => blah
)
[1] => Array
(
[id] => 6
[szn_data] => blah
)
[2] => Array
(
[id] => 5
[gcz_data] => blah
)
[3] => Array
(
[id] => 3
[gcz_data] => blah
)
[4] => Array
(
[id] => 2
[zbo_data] => blah
)
[5] => Array
(
[id] => 1
[szn_data] => blah
)
And I need to sort it by group of 3 in this order: szn_data, zbo_data, gcz_data but I also need to keep the order of [id] (basically primary order by szn_data, zbo_data, gcz_data, secondary [id]). Is there a solution? Or should I construct array differently to be able to sort it? I am trying to figure this out for over 6 hours. Any help is much appreciated.
My desired output is:
[0] => Array
(
[id] => 6
[szn_data] => blah
)
[1] => Array
(
[id] => 8
[zbo_data] => blah
)
[2] => Array
(
[id] => 5
[gcz_data] => blah
)
[3] => Array
(
[id] => 1
[szn_data] => blah
)
[4] => Array
(
[id] => 2
[zbo_data] => blah
)
[5] => Array
(
[id] => 3
[gcz_data] => blah
)
Use usort and implement your comparison function as you wish. For example:
$result = usort($arr, function($a,$b) {
$keys = array('szn_data', 'zbo_data', 'gcz_data');
foreach ($keys as $key) {
// make sure to add here handling of missing keys
$diff = strcmp($b[$key], $a[$key]);
if ($diff!=0) {
return $diff;
}
}
return $b['id'] - $a['id'];
});
Or like this, for any order from max to the min listed in one array
$arr = array (
array(
'id' => 8,
'zbo_data' => 'blah'
),
array(
'id' => 6,
'szn_data' => 'blah'
),
array(
'id' => 5,
'gcz_data' => 'blah'
),
array(
'id' => 3,
'gcz_data' => 'blah'
),
array(
'id' => 2,
'zbo_data' => 'blah'
),
array(
'id' => 1,
'szn_data' => 'blah'
)
);
usort($arr, "my_func");
var_dump($arr);
function my_func($a, $b)
{
$vars = array('szn_data', 'zbo_data', 'gcz_data'); // order of the keys
$id1 = $a['id']; $id2 = $b['id']; unset($a['id'], $b['id']);
$index1 = array_search(key($a), $vars);
$index2 = array_search(key($b), $vars);
if ($index1 == $index2) {
if ($id1 == $id2) return 0;
return ($id1 < $id2) ? 1 : -1;
}
return ($index1 < $index2) ? -1 : 1;
}
ps:
basically primary order by szn_data, zbo_data, gcz_data, secondary
[id]
It does not correspond to your desired output. Secondary means comparison of id when other keys are the same.
ps: Updated - this code is NOT nice or perfect, but it will give you what you need
$vars = array('szn_data', 'zbo_data', 'gcz_data');
$arr = array (
array(
'id' => 8,
'zbo_data' => 'blah'
),
array(
'id' => 6,
'szn_data' => 'blah'
),
array(
'id' => 5,
'gcz_data' => 'blah'
),
array(
'id' => 3,
'gcz_data' => 'blah'
),
array(
'id' => 2,
'zbo_data' => 'blah'
),
array(
'id' => 1,
'szn_data' => 'blah'
)
);
$temp = array();
$cnt = count($arr);
foreach($arr as $item)
{
foreach($vars as $v)
{
if (isset($item[$v])) { $temp[$v][$item['id']] = $item; break; }
}
}
// sort by id
foreach($vars as $v)
{
krsort($temp[$v]);
$temp[$v] = array_values($temp[$v]);
}
$arr = array(); $i = 0; $j = 0;
$completed = false;
do {
foreach($vars as $v)
{
if ($i++>=$cnt) { $completed = true; break; }
if (isset($temp[$v][$j])) $arr[] = $temp[$v][$j];
}
$j++;
} while (!$completed);
// output
var_dump($arr)

array transformation in php

how would you turn this array:
Array
(
[0] => 234234234
[1] => 657567567
[2] => 234234234
[3] => 5674332
)
into this:
Array
(
[contacts] => Array(
[0] => Array
(
[number] => 234234234
[contact_status] => 2
[user_id] =>3
)
[1] => Array
(
[number] => 657567567
[contact_status] => 2
[user_id] =>3
)
[3] => Array
(
[number] => 234234234
[contact_status] => 2
[user_id] =>3
)
[4] => Array
(
[number] => 5674332
[contact_status] => 2
[user_id] =>3
)
)
)
is there a cakephp specific way how to transform this array?
thank you
nicer
$contact_status = 2;
$user_id = 1;
foreach($input as $number)
$output['contacts'][] = compact('number', 'contact_status', 'user_id');
Try this:
$output = array('contacts'=>array());
foreach ($input as $val) {
$output['contacts'][] = array(
'number' => $val,
'contact_status' => 2,
'user_id' => 3
);
}
I assume that contact_status and user_id are static since you didn’t tell anything else.
$input = array(...);
$arr = array();
foreach ($input as $id) {
$arr[] = array(
'number' => $id,
'contact_status' => 2,
'userid' => 3;
);
}
$output = array('contacts' => $arr);
A little bit of cleanup from sterofrog's solution. Declare the array and use array_push instead of assigning it to an empty index.
$output = array( );
$contact_stats = 2;
$user_id = 3;
foreach( $input as $number ) {
array_push( $output[ 'contact' ], compact(
'number',
'contact_status',
'user_id'
));
}
You can simply use the array_map function like this:
$result = array_map(function ($n){
return array(
'number' => $n,
'contact_status' => 2,
'user_id' => 3);
}, $original);

Categories