Remove specific string from whole associative array items - php

I have an associative array. I want to remove specific string from whole array items. Here is the structure of my array:
Array
(
[50808] => Array
(
[quantity] => 2
[name] => asv (test)
)
[50809] => Array
(
[quantity] => 2
[name] => 37 (test)
)
[50810] => Array
(
[quantity] => 3
[name] => 38 (test)
)
)
Output i want:
Array
(
[50808] => Array
(
[quantity] => 2
[name] => asv
)
[50809] => Array
(
[quantity] => 2
[name] => 37
)
[50810] => Array
(
[quantity] => 3
[name] => 38
)
)
I know its very simple using loop but i want to do it without loop.

Use array_map function
<?php
$array = Array
(
'50808' => Array
(
'quantity' => 2,
'name' => 'asv (test)',
),
'50809' => Array
(
'quantity' => 2,
'name' => '37 (test)'
),
'50810' => Array
(
'quantity' => 3,
'name' => '38 (test)'
)
);
echo '<pre>';
$new_array = array_map(function($val){
$val['name'] = trim(str_replace('(test)', '', $val['name']));
return $val;
}, $array);
print_r($new_array);
Output:
Array
(
[50808] => Array
(
[quantity] => 2
[name] => asv
)
[50809] => Array
(
[quantity] => 2
[name] => 37
)
[50810] => Array
(
[quantity] => 3
[name] => 38
)
)
Another method can be array_walk function:
array_walk($array, function(&$val){
$val['name'] = trim(str_replace('(test)', '', $val['name']));
});
print_r($array); //out put: desired output

Related

PHP Array Unique Sort Regular not working as expected

I'm using print_r(array_unique($array, SORT_REGULAR)); on the array below but it does not work.
I'm trying to filter out the redundant data.
Notice that [Order] and its key value pairs are all the same. But [Transaction] and its key value pairs are unique.
I need to get the [Order] element data and combine it with the 3 different [Transaction] elements.
My array
Array
(
[0] => Array
(
[Order] => Array
(
[PO] => TR11214
[OrderID] => 242856952012
)
[Transaction] => Array
(
[TransPO] => TR11211
[TransactionPrice] => 91.17
)
)
[1] => Array
(
[Order] => Array
(
[PO] => TR11214
[OrderID] => 242856952012
)
[Transaction] => Array
(
[TransPO] => TR11212
[TransactionPrice] => 180.41
)
)
[2] => Array
(
[Order] => Array
(
[PO] => TR11214
[OrderID] => 242856952012
)
[Transaction] => Array
(
[TransPO] => TR11213
[TransactionPrice] => 209.99
)
)
)
The final array I need will look something like this.
Array
(
[Order] => Array
(
[PO] => TR11214
[OrderID] => 242856952012
)
[Transaction] => Array
(
[0] => Array
(
[TransPO] => TR11211
[TransactionPrice] => 91.17
)
[1] => Array
(
[TransPO] => TR11212
[TransactionPrice] => 180.41
)
[2] => Array
(
[TransPO] => TR11213
[TransactionPrice] => 209.99
)
)
)
I can flatten the original array and then use array_unique, but wanted to see if there is a better way to accomplish what I need.
my code:
$myarray = array(
0 => array(
"Order" => array("PO" => "TR11214", "OrderID" => 242856952012),
"Transaction" => array("TransPO" => "TR11211", "TransactionPrice" => 91.17)
),
1 => array(
"Order" => array("PO" => "TR11214", "OrderID" => 242856952012),
"Transaction" => array("TransPO" => "TR11212", "TransactionPrice" => 180.41)
),
2 => array(
"Order" => array("PO" => "TR11214", "OrderID" => 242856952012),
"Transaction" => array("TransPO" => "TR11213", "TransactionPrice" => 209.99)
)
);
print_r(array_unique($myarray, SORT_REGULAR));
If you want to determine how many unique values of the Order element there are in your array, you need to apply array_unique only to the Order elements, which you can do using array_column:
$unique_orders = count(array_unique(array_column($myarray, 'Order'), SORT_REGULAR));
You can process your array using a list of keys which have non-unique values to generate an array, while other keys will have just a single value:
$non_unique_keys = ['Transaction'];
$output = array();
foreach (array_keys($myarray[0]) as $key) {
if (in_array($key, $non_unique_keys)) {
$output[$key] = array_column($myarray, $key);
}
else {
$output[$key] = $myarray[0][$key];
}
}
print_r($output);
Example Output:
Array (
[Order] => Array (
[PO] => TR11214
[OrderID] => 242856952012
)
[Sales Tax] => Array (
[PO] => TR11214
[SalesTaxAmount] => 0
)
[Transaction] => Array (
[0] => Array (
[TransPO] => TR11211
[TransactionPrice] => 91.17
)
[1] => Array (
[TransPO] => TR11212
[TransactionPrice] => 180.41
)
[2] => Array (
[TransPO] => TR11213
[TransactionPrice] => 209.99
)
)
)
Demo on 3v4l.org
array_unique() is intended for single dimensional arrays. If you want to use it on a multi-dimentional array, you should consider using usort() instead. Then you'll need to iterate through the array in reverse manually, searching for duplicates and removing them.

Multidimensional array to single array in PHP

I am working in PHP so I have an array like this, from this array I want filter take user_id to another array like I given below.
Array
(
[0] => Array
(
[user_id] => 66
[distance] => 0
)
[1] => Array
(
[user_id] => 68
[distance] => 0
)
[2] => Array
(
[user_id] => 81
[distance] => 0
)
[3] => Array
(
[user_id] => 65
[distance] => 0.00010218008081861118
)
)
I want an array like this,
$user_id=array(66,68,81,65);
Use array_column()
Returns an array of values representing a single column from the input array.
<?php
$user_array = array(
0 => array('user_id' => 1, 'name' => 'Bob'),
1 => array('user_id' => 2, 'name' => 'John'),
2 => array('user_id' => 3, 'name' => 'Mary')
);
$users = array_column($user_array, 'user_id');
print_r($users);
Output :
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Where $array is the multidimensional array you provided above:
$data = array();
foreach ($array as $item) {
$data[] = $item['user_id'];
}
print_r($data);

Change array key and group key with the same value

I have an array looks like this:
Array
(
[0] => Array
(
[variant_name] => Green
[product_id] => 2
[variant_id] => 67
[amount] => 1000
)
[1] => Array
(
[variant_name] => Red
[product_id] => 2
[variant_id] => 68
[amount] => 0
)
)
This expected to be like this:
Array (
[2] => array (
[67] => array (
[variant_id] => Green
[amount] => 1000
(
[68] => array (
[variant_id] => Red
[amount] => 0
(
)
Which is group by product_id and then split into arrays group by variant_id.
How can I do that.
Thank you so much.
foreach($values as $product)
{
$newValues[$product["product_id"]][$product["variant_id"]]=
array(
'product_name'=>$product["variant_name"],
'amount'=>$product["amount"]
);
}
Output
Array
(
[2] => Array
(
[67] => Array
(
[product_name] => Green
[amount] => 1000
)
[68] => Array
(
[product_name] => Red
[amount] => 0
)
)
)
Note You have variant_name in your original array and you are using that as variant_id in your output. You can play with indexes in this code. I just used what seemed to match.
A simple foreach loop should suffice. Of course, you need to build them inside a new array. Consider this example: (In your expected example, I think you were referring to variant_name)
$values = array( array( 'variant_name' => 'Green', 'product_id' => 2, 'variant_id' => 67, 'amount' => 1000, ), array( 'variant_name' => 'Red', 'product_id' => 2, 'variant_id' => 68, 'amount' => 0, ), );
$new_values = array();
foreach($values as $key => $value) {
$new_values[$value['product_id']][$value['variant_id']] = array(
'variant_name' => $value['variant_name'],
'amount' => $value['amount'],
);
}
echo '<pre>';
print_r($new_values);
echo '</pre>';
Sample Output

building a multidimensional array from mysql with php

I am trying to form a specific multidimensional array from a mysql result set.
I would like it to look like this:
array(
'product_name' => 'prod_1',
'categories' => array(1,2,3,4)
);
The db result return an array that looks something like this
Array
(
[0] => Array
(
[id] => 1
[product_name] => prod_1
)
[1] => Array
(
[id] => 2
[product_name] => prod_1
)
[2] => Array
(
[id] => 3
[product_name] => prod_1
)
[3] => Array
(
[id] => 4
[product_name] => prod_1
)
As you can see, i would like to group the product name and place the id into another array
Does anyone have any tips on how to do this?
$yourarray = array(array('id'=>1, 'product_name' => 'prod_1'), array('id'=>2, 'product_name' => 'prod_2'),array('id'=>3, 'product_name' => 'prod_3'));
$multiarray = array();
for($i=0; $i<count($yourarray);$i++){
$multiarray['product_name'][] = $yourarray[$i]['product_name'];
$multiarray['product_id'][] = $yourarray[$i]['id'];
}
print_r($yourarray); //original array
print_r($multiarray); //gives you multi array
Something similar to this?
Your original array:
Array
(
[0] => Array
(
[id] => 1
[product_name] => prod_1
)
[1] => Array
(
[id] => 2
[product_name] => prod_2
)
[2] => Array
(
[id] => 3
[product_name] => prod_3
)
)
The result would print:
Array
(
[product_name] => Array
(
[0] => prod_1
[1] => prod_2
[2] => prod_3
)
[product_id] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
Did you try GROUP_CONCAT. It's something like:
SELECT name, GROUP_CONCAT(name) AS friends FROM friendships GROUP BY name;
Have a look for details here: http://forums.mysql.com/read.php?10,287931,287936#msg-287936
$yourarray = array(array('id'=>1, 'product_name' => 'prod_1'), array('id'=>2, 'product_name' => 'prod_1'), array('id'=>3, 'product_name' => 'prod_1'),array('id'=>4, 'product_name' => 'prod_1'));
$multiarray = array();
foreach ($yourarray as $value) {
if(!isset($multiarray['product_name'])) {
$multiarray['product_name'] = $value['product_name'];
}
$multiarray['categories'][] = $value['id'];
}
print_r($multiarray);

How do i merge the arrays in a particular format?

I have following arrays:
1) for total placed
Array
(
[0] => Array
(
[centers] => Array
(
[name] => delhi
[id] => 1
)
[0] => Array
(
[totalplaced] => 8
)
)
[1] => Array
(
[centers] => Array
(
[name] => mumbai
[id] => 2
)
[0] => Array
(
[totalplaced] => 1
)
)
)
2) for total working
Array
(
[0] => Array
(
[centers] => Array
(
[name] => delhi
[id] => 1
)
[0] => Array
(
[totalworking] => 4
)
)
[1] => Array
(
[centers] => Array
(
[name] => mumbai
[id] => 2
)
[0] => Array
(
[totalworking] => 1
)
)
)
3) for total trained
Array
(
[0] => Array
(
[centers] => Array
(
[name] => delhi
[id] => 1
)
[0] => Array
(
[totaltrained] => 8
)
)
[1] => Array
(
[centers] => Array
(
[name] => mumbai
[id] => 2
)
[0] => Array
(
[totaltrained] => 1
)
)
)
I wanted to merge these arrays so that the resultant array should look like this
[newarray] => Array(
[0] => Array (
[centers] => Array
(
[name] => delhi
[id] => 1
[totalplaced] => 8
[totalworking] => 4
[totaltrained] => 8
)
)
[1]=> Array(
[centers] => Array
(
[name] => mumbai
[id] => 2
[totalplaced] => 1
[totalworking] => 1
[totaltrained] => 1
)
)
)
This is the tabular representation of the above data which i want to display
centername totalplaced totalworking totaltrained
delhi 8 4 8
mumbai 1 1 1
Please help me on this.
Thanks
Pankaj Khurana
The difficulty here is that PHP's functions such as array_merge() and array_merge_recursive() will not merge data into numeric keys, but rather will re-key any duplicate numeric key. So for example given two arrays:
array(
'test' => 'abc',
0 => 'xyz'
);
array(
'test' => 'def',
0 => 'uvw'
);
Merging them together with array_merge() will produce an array like:
array(
'test' => 'def',
0 => 'xyz',
1 => 'uvw'
);
So, you need a custom function to be "additive" on any key, regardless of whether it is a string or numeric key. Try this:
function mixed_key_array_merge() {
$args = func_get_args();
$result = array();
foreach ($args as $arg) {
// discard non-array arguments; maybe this could be better handled
if (!is_array($arg)) {
continue;
}
foreach ($arg as $key => $value) {
if (!isset($result[$key])) {
$result[$key] = $value;
} else if (is_array($result[$key])) {
$result[$key] = call_user_func_array('mixed_key_array_merge',array($result[$key],$value));
}
}
}
return $result;
}

Categories