This question already has answers here:
PHP - Replace data within multidimensional array, specific key
(2 answers)
How to replace a value in multidimensional array - PHP
(1 answer)
Closed 3 years ago.
I have this kind of array:
Array
(
[0] => Array
(
[title] => Personal
[closeable] => 1
[visible] => 1
)
[1] => Array
(
[title] => My contracts
[closeable] => 1
[visible] => 1
)
[2] => Array
(
[title] => Info
[closeable] => 1
[visible] => 1
)
)
I need to replace one word in the array - My contracts for something else.
My contracts will be always there, but the order may change, so I must check for the exact name and replace it.
I tried it via str_replace($value, $replacement, $array);
also via
$ar = array_replace($ar,
array_fill_keys(
array_keys($ar, $value),
$replacement
)
);
and finally:
array_map(function ($v) use ($value, $replacement) {
return $v == $value ? $replacement : $v;
}, $arr);
Nothing worked. So how can I replace that one word?
foreach ($ar as &$item) {
if ($item['title'] === 'My contracts') {
$item['title'] = 'Some new value';
// if you're sure that record will be met ONCE
// you can add `break;` to stop looping
}
}
If you want to use array_walk, you can approach as
$stringToFind = 'My contracts';
$stringToReplace = 'REPLACMENT';
array_walk($arr, function(&$v,$k) use ($stringToFind,$stringToReplace){
($v['title'] == $stringToFind) ? ($v['title'] = $stringToReplace) : '';
});
Related
This question already has answers here:
How can I remove duplicates in an object array in PHP?
(2 answers)
Closed 8 years ago.
When I print $online_performers variable I want to get a unique value for id 2. Do I need to convert them in standard array first or is that possible without it? (remove all duplicates).Please check my new code for this.
Array
(
[0] => stdClass Object
(
[id] => 1
[username] => Sample1
)
[1] => stdClass Object
(
[id] => 2
[username] => Sample1
)
[2] => stdClass Object
(
[id] => 2
[username] => Sample1
)
[3] => stdClass Object
(
[id] => 4
[username] => Sample4
)
)
to
Array
(
[0] => stdClass Object
(
[id] => 1
[username] => Sample1
)
[1] => stdClass Object
(
[id] => 4
[username] => Sample4
)
)
PHP has a function called array_filter() for that purpose:
$filtered = array_filter($array, function($item) {
static $counts = array();
if(isset($counts[$item->id])) {
return false;
}
$counts[$item->id] = true;
return true;
});
Note the usage of the static keyword. If used inside a function, it means that a variable will get initialized just once when the function is called for the first time. This gives the possibility to preserve the lookup table $counts across multiple function calls.
In comments you told, that you also search for a way to remove all items with id X if X appears more than once. You could use the following algorithm, which is using a lookup table $ids to detect elements which's id occur more than ones and removes them (all):
$array = array("put your stdClass objects here");
$ids = array();
$result = array();
foreach($array as $item) {
if(!isset($ids[$item->id])) {
$result[$item->id]= $item;
$ids[$item->id] = true;
} else {
if(isset($result[$item->id])) {
unset($result[$item->id]);
}
}
}
$result = array_values($result);
var_dump($result);
If you don't care about changing your keys you could do this with a simple loop:
$aUniq = array ();
foreach($array as $obj) {
$aUniq[$obj->id] = $obj;
}
print_r($aUniq);
Let's say we have:
$array = [
//items 1,2,3 are same
(object)['id'=>1, 'username'=>'foo'],
(object)['id'=>2, 'username'=>'bar'],
(object)['id'=>2, 'username'=>'baz'],
(object)['id'=>2, 'username'=>'bar']
];
Then duplication depends of what do you mean. For instance, if that's about: two items with same id are treated as duplicates, then:
$field = 'id';
$result = array_values(
array_reduce($array, function($c, $x) use ($field)
{
$c[$x->$field] = $x;
return $c;
}, [])
);
However, if that's about all fields, which should match, then it's a different thing:
$array = [
//1 and 3 are same, 2 and 3 are not:
(object)['id'=>1, 'username'=>'foo'],
(object)['id'=>2, 'username'=>'bar'],
(object)['id'=>2, 'username'=>'baz'],
(object)['id'=>2, 'username'=>'bar']
];
You'll need to identify somehow your value row. Easiest way is to do serialize()
$result = array_values(
array_reduce($array, function($c, $x)
{
$c[serialize($x)] = $x;
return $c;
}, [])
);
But that may be slow since you'll serialize entire object structure (so you'll not see performance impact on small objects, but for complex structures and large amount of them it's sounds badly)
Also, if you don't care about keys in resulting array, you may omit array_values() call, since it serves only purpose of making keys numeric consecutive.
This question already has answers here:
Deleting an element from an array in PHP
(25 answers)
Closed 8 years ago.
I want to search an associative array and when I find a value, delete that part of the array.
Here is a sample of my array:
Array
(
[0] => Array
(
[id] => 2918
[schoolname] => Albany Medical College
[AppService] => 16295C0C51D8318C2
)
[1] => Array
(
[id] => 2919
[schoolname] => Albert Einstein College of Medicine
[AppService] => 16295C0C51D8318C2
)
[2] => Array
(
[id] => 2920
[schoolname] => Baylor College of Medicine
[AppService] => 16295C0C51D8318C2
)
}
What I want to do is find the value 16295C0C51D8318C2 in the AppService and then delete that part of the array. So, for example, if that code was to run on the above array, it was empty out the entire array since the logic matches everything in that array.
Here is my code so far:
foreach($this->schs_raw as $object) {
if($object['AppService'] == "16295C0C51D8318C2") {
unset($object);
}
}
array_filter will help (http://php.net/manual/en/function.array-filter.php)
$yourFilteredArray = array_filter(
$this->schs_raw,
function($var) {
return $object['AppService'] != "16295C0C51D8318C2"
}
);
Try like this:
foreach ($this->schs_raw as &$object) {
if($object['AppService'] == "16295C0C51D8318C2") {
unset($object);
}
}
Eventually:
foreach ($this->schs_raw as $k => $object) {
if($object['AppService'] == "16295C0C51D8318C2") {
unset($this->schs_raw[$k]);
}
}
Try this:
foreach($this->schs_raw as $key=>$object) {
if($object['AppService'] == "16295C0C51D8318C2") {
unset($this->schs_raw[$key]); // unset the array using appropriate index
break; // to exit loop after removing first item
}
}
Why not create a new array? If match not found, add index to new array... If it is found, don't add it. Your new array will only contain the data you want.
This question already has answers here:
Remove duplicates from Array
(2 answers)
Closed 9 years ago.
I have an array like this
Array
(
[0] => u1,u2
[1] => u2,u1
[2] => u4,u3
[3] => u1,u3
[4] => u1,u2
)
I want to remove similar values from the array
I want an out put like
Array
(
[0] => u1,u2
[1] => u4,u3
[2] => u1,u3
)
I tried to loop thru the input array, sort the value of the indexes alphabetically and then tried array_search to find the repeated values. but never really got the desired output
any help apprecated
You cannot use array_unique() alone, since this will only match exact duplicates only. As a result, you'll have to loop over and check each permutation of that value.
You can use array_unique() to begin with, and then loop over:
$myArray = array('u1,u2', 'u2,u1', 'u4,u3', 'u1,u3', 'u1,u2');
$newArr = array_unique($myArray);
$holderArr = array();
foreach($newArr as $val)
{
$parts = explode(',', $val);
$part1 = $parts[0].','.$parts[1];
$part2 = $parts[1].','.$parts[0];
if(!in_array($part1, $holderArr) && !in_array($part2, $holderArr))
{
$holderArr[] = $val;
}
}
$newArr = $holderArr;
The above code will produce the following output:
Array (
[0] => u1,u2
[1] => u4,u3
[2] => u1,u3
)
Use array_unique() PHP function:
http://php.net/manual/en/function.array-unique.php
Use the function array_unique($array)
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
php manual
since u1,u2 !== u2,u1
$array=array('u1,u2','u2,u1','u4,u3','u1,u3','u1,u2');
foreach($array as $k=>$v)
{
$sub_arr = explode(',',$v);
asort($sub_arr);
$array[$k] = implode(',',$sub_arr);
}
$unique_array = array_unique($array);
//$unique_array = array_values($unique_array) //if you want to preserve the ordered keys
I have an array with the following values
- Array ( [id] => 3 [parent_id] => 2 [name] => Fitness )
- Array ( [id] => 4 [parent_id] => 3 [name] => Why do it)
- Array ( [id] => 5 [parent_id] => 3 [name] => Nutrition)
Id like to query it along the lines of
array_search([parent_id]='3', $array)
and return a list of matching elements. (In this instance it would be id's 4 & 5). I'm not sure if array_search() is the right way to go about this. May attempts are failing at moment.
<?php
function mySearchArr($key, $value, $myBigArr) {
$searchArr = array();
foreach($myBigArr as $smallArr)
if($smallArr[$key] == $value)
$searchArr[] = $smallArr;
return $searchArr
}
$matches = mySearchArr('parent_id', 3, $array);
?>
You could use array_filter with a custom callback
$lookup_id = 3;
$results = array_filter($your_array, function($arr) use ($lookup_id) {
return $your_array['parent_id'] == $lookup_id;
});
This code requires i believe >=PHP5.3, if you have an older version, you will have to implement the callback using either an actual defined function (normal php function), or using create_function
I have a large array of scraped names and prices similar to the following:
Array([0] => apple3 [1] => £0.40 [2] => banana6 [3] => £1.80 [4] => lemon [5] => grape [6] => pear5 [7] => melon4 [8] => £2.32 [9] => kiwi [10] => £0.50)
I would like to remove the fruit names that are not immediately followed by a price. In the above example this would remove: [4] => lemon [5] => grape [6] => pear5 resulting in the following output:
Array([0] => apple3 [1] => £0.40 [2] => banana6 [3] => £1.80 [7] => melon4 [8] => £2.32 [9] => kiwi [10] => £0.50)
If the array needs to be converted to a string in order for me to do this that is not a problem, nor is adding values between the array items in order to aid with regex searches. I have so far been unable to find the correct regular expression to do this using preg_match and preg_replace.
The most important factor is the need to maintain the sequential order of the fruits and prices in order for me at a later stage to convert this into an associative array of fruits and prices.
Thanks in advance.
Why involve regular expressions? This is doable with a simple foreach loop wherein you iterate over the array and remove names that follow names:
$lastWasPrice = true; // was the last item a price?
foreach ($array as $k => $v) {
if (ctype_alpha($v)) {
// it's a name
if (!$lastWasPrice) {
unset($array[$k]); // name follows name; remove the second
}
$lastWasPrice = false;
}
else {
// it's a price
$lastWasPrice = true;
}
}
The following code does both of your tasks at once: getting rid of the fruit without value and turning the result into an associative array of fruits with prices.
$arr = array('apple', '£0.40', 'banana', '£1.80', 'lemon', 'grape', 'pear', 'melon', '£2.32', 'kiwi', '£0.50' );
preg_match_all( '/#?([^£][^#]+)#(£\d+\.\d{2})#?/', implode( '#', $arr ), $pairs );
$final = array_combine( $pairs[1], $pairs[2] );
print_r( $final );
First, the array is converted to a string, separated by '#'. The regex captures all groups of fruits with prices - each stored as a separate subgroup in the result. Combining them into an associative array is a single function call.
Something like this might help you
$array = ...;
$index = 0;
while (isset($array[$index + 1])) {
if (!is_fruit($array[$index + 1])) {
// Not followed by a fruit, continue to next pair
$index += 2;
} else {
unset($array[$index]); // Will maintain indices in array
$index += 1;
}
}
Not tested though. Also, you need to create the function is_fruit yourself ;)
Without reformatting it, I don't think you can do it with preg_match or preg_replace-- maybe, but nothing is coming to mind.
What is creating that array? If possible, I would alter it to look more like:
Array([apple] => £0.40 [banana] => £1.80 [lemon] => [grape] => '' [pear ] => '' [melon => £2.32 [kiwi] => £0.50)
Then array_filter($array) is all you'd need to clean it up. If you can't alter the way the original array is created I'd lean towards creating key/value array out of the original.
Try replacing the pattern ** => ([a-zA-Z])** with ** => £0.00 $1**
Basically searching for the context where there is null price and inserting zero pounds.
Hope this helps.
Good luck
Simply do this :
<?php
for($i=0;$i<count($my_array);$i++)
{
if($my_array[$i+1]value=="")
unset($my_array[$i])
}
?>
assume $a is your array.
function isPrice($str) {
return (substr($str, 0, 1) == '£');
}
$newA = array();
for($i=0;$i<count($a);$i++) {
if( isPrice($a[$i]) != isPrice($a[$i+1]) ){
$newA[] = $a[$i];
}
}