How do I remove one array from another in php? - php

I have the following arrays in PHP:
print_r($employees) =
Array
(
[0] => Array
(
[p_id] => T29083999
[name] => Robert Plaxo
)
[1] => Array
(
[p_id] => T29083388
[name] => Yvan Sergei
)
[2] => Array
(
[p_id] => T21083911
[name] => Rhonda Saunders
)
[3] => Array
(
[p_id] => H02910382
[name] => Miguel Mercado
)
)
then this array:
print_r($record) =
Array
(
[0] => Array
(
[c_id] => 1
[section] => 1061
[term] => 201631
[p_id] => T29083388
[c_date] => 2016-04-01 09:14:00
)
)
I want to remove the array element from $employees that matches the p_id of $record. Array $record may have multiple entries like the one shown. If so, any p_id in $record must be removed from $employees.
I tried:
foreach ($employees as $k => $e) {
foreach ($record as $r) {
if ($e['p_id']==$r['p_id']) {
echo "found it!";
// if I uncomment the next line, it crashes! (500 server error)
// unset $employees[$k];
}
}
}
I just want to remove any element from $employees that has any employee that matches any record in $record with that employee id.

You were almost there; just needed parens around your unset()
I also took the liberty to change some of your variable names as single character variable names bother me.
$employees[] = [
'p_id' => 'T29083999',
'name' => 'Robert Plaxo',
];
$employees[] = [
'p_id' => 'T29083388',
'name' => 'Yvan Sergei',
];
$employees[] = [
'p_id' => 'T21083911',
'name' => 'Rhonda Saunders',
];
$employees[] = [
'p_id' => 'H02910382',
'name' => 'Miguel Mercado',
];
$records[] = [
'c_id' => '1',
'section' => '1061',
'term' => '201631',
'p_id' => 'T29083388',
'c_date' => '2016-04-01 09:14:00',
];
foreach ($employees as $key => $employee) {
foreach ($records as $record) {
if ($employee['p_id'] == $record['p_id']) {
echo "found it!";
unset($employees[$key]);
}
}
}
echo "<pre>";
print_r($employees);
Outputs
found it!
Array
(
[0] => Array
(
[p_id] => T29083999
[name] => Robert Plaxo
)
[2] => Array
(
[p_id] => T21083911
[name] => Rhonda Saunders
)
[3] => Array
(
[p_id] => H02910382
[name] => Miguel Mercado
)
)

The short solution using array_column and array_filter functions. It will also fit your requirement "Array $record may have multiple entries":
$p_ids = array_column($record, "p_id");
$employees = array_filter($employees, function($v) use($p_ids){
return !in_array($v["p_id"], $p_ids);
});
print_r($employees);
The output:
Array
(
[0] => Array
(
[p_id] => T29083999
[name] => Robert Plaxo
)
[2] => Array
(
[p_id] => T21083911
[name] => Rhonda Saunders
)
[3] => Array
(
[p_id] => H02910382
[name] => Miguel Mercado
)
)

Related

PHP associative array- matched key value of each array will be a table row

I have an array like this-
Array
(
[sku] => Array
(
[0] => SKU125
[1] => SKU121
[2] => SKU122
[3] => SKU124
)
[variation_description] => Array
(
[0] => test another
[1] => test
[2] => test
[3] => test
)
[price_html] => Array
(
[0] => 400,200
[1] => 500
[2] => 600,300
[3] => 700
)
)
Is it possible to covert the array to like this table-
Any kind of help will be appreciated.
Thanks In Advance
As every key (sku , price_html etc) has same amount of data , so just push the corresponding key data to a new array.
$data = [
'sku' => ['SKU125', 'SKU121', 'SKU122', 'SKU124'],
'variation_description' => ['test another', 'test', 'test', 'test'],
'price_html' => ['400,200', '500', '600,300', '700']
];
$re_structured = [];
foreach ($data as $each_key_data ) {
foreach ($each_key_data as $key => $value2 ) {
$re_structured[$key][] = $value2;
}
}
var_dump($re_structured);
You can simply iterate through data and create a new array.
$data = [
'sku' => ['SKU125', 'SKU121', 'SKU122', 'SKU124'],
'variation_description' => ['test another', 'test', 'test', 'test'],
'price_html' => ['400,200', '500', '600,300', '700']
];
$mapped = [];
$keys = array_keys($data);
$rows = count($data[reset($keys)]);
for ($i = 0; $i < $rows; $i++) {
$row = [];
foreach ($keys as $key)
$row[] = $data[$key][$i];
$mapped[] = $row;
}
This will result in
print_r($mapped);
Array
(
[0] => Array
(
[0] => SKU125
[1] => test another
[2] => 400,200
)
[1] => Array
(
[0] => SKU121
[1] => test
[2] => 500
)
[2] => Array
(
[0] => SKU122
[1] => test
[2] => 600,300
)
[3] => Array
(
[0] => SKU124
[1] => test
[2] => 700
)
)

Combining duplicate keys in a multidimensional array in PHP [duplicate]

This question already has answers here:
Group subarrays by one column, make comma-separated values from other column within groups
(2 answers)
Closed last month.
here's how it looks in the PHP code:
<?php
$array = array(
array(
'name' => 'filter_amount',
'value' => '100-ml'
),
array(
'name' => 'filter_amount',
'value' => '200-ml'
),
array(
'name' => 'page_size',
'value' => '7'
)
);
print_r($array);
?>
Example of print_r() function output:
Array
(
[0] => Array
(
[name] => filter_amount
[value] => 100-ml
)
[1] => Array
(
[name] => filter_amount
[value] => 200-ml
)
[2] => Array
(
[name] => page_size
[value] => 7
)
)
I need to combine duplicates of filter_amount values from the array.
The values of these duplicates must be commas separated and the result should be the following code:
Array
(
[0] => Array
(
[name] => filter_amount
[value] => 100-ml,200-ml
)
[1] => Array
(
[name] => page_size
[value] => 7
)
[2] => Array
(
[name] => orderby
[value] => rating
)
[3] => Array
(
[name] => paged
[value] => 1
)
)
Since you want value to be concatenated by a comma, you'll have to make a cycle of it
<?php
//Allow me to change this variable name, just to not create confusion
$content = array(
array(
'name' => 'filter_amount',
'value' => '100-ml'
),
array(
'name' => 'filter_amount',
'value' => '200-ml'
),
array(
'name' => 'page_size',
'value' => '7'
)
);
//$content is your initial array
//$outputArray is the final worked-up array
$outputArray = [];
//Let's make a cycle going for every array inside $content
foreach ($content as $innerArray) {
//Does this $innerArray['name'] (filter_ammount) exist in $outputArray in an array
//consisting in key => value where the key is 'name' and equals
//what we look for that is(filter_ammount)?
$key = array_search($innerArray['name'], array_column($outputArray , 'name'));
//If not, let's place this array in the $output array
if ($key === false) {
array_push($outputArray, $innerArray);
} else {
//If exists, then $key is the $key of the $outputArray and let's add to its value
//our current value, that is in our $innerArray, concatenated with a comma
$outputArray[$key]['value'] .= ",". $innerArray['value'];
}
}
//Boom, magic
print_r($outputArray);
//Note: This is going to affect every duplicate it finds, as in:
//If you got 3 arrays with name 'filter_ammount' and 2 arrays with name
//'page_size', it's going to concatenate the filter_ammount and the 'page_size'.
//If you specifically just want filter_ammount,
//replace this -> $key = array_search($innerArray['name'], array_column($outputArray , 'name'));
//with this -> $key = array_search('filter_ammount', array_column($outputArray , 'name'));
?>
References
http://php.net/manual/en/function.array-search.php
http://php.net/manual/en/function.array-column.php
How to combine two items by 2 duplicate columns?
[root#localhost TEST]# php R00.php
Array
(
[0] => Array
(
[0] => S01
[1] => 172.16.20.222
[2] => 10.10.10.100
[3] => 445
)
[1] => Array
(
[0] => S02
[1] => 10.10.10.10
[2] => 192.168.100.100
[3] => 22
)
[2] => Array
(
[0] => S03
[1] => 10.10.10.10
[2] => 192.168.100.100
[3] => 22
)
[3] => Array
(
[0] => S04
[1] => 172.16.20.222
[2] => 10.10.10.100
[3] => 23
)
[4] => Array
(
[0] => S05
[1] => 100.100.100.100
[2] => 192.168.100.100
[3] => 22
)
[5] => Array
(
[0] => S06
[1] => 192.168.200.10
[2] => 192.168.100.100
[3] => 22
)
[6] => Array
(
[0] => S07
[1] => 10.10.10.10
[2] => 192.168.100.100
[3] => 22
)
[7] => Array
(
[0] => S08
[1] => 192.168.100.100
[2] => 10.10.100.106
[3] => 446
)
[8] => Array
(
[0] => S09
[1] => 172.16.20.223
[2] => 10.10.10.108
[3] => 447
)
[9] => Array
(
[0] => S10
[1] => 192.168.100.100
[2] => 10.10.10.109
[3] => 448
)
)
[root#localhost TEST]#
combine 1 or 2 items by 2 column duplicate below is result I need
Array
(
[0] => Array
(
[0] => S01 , S04
[1] => 172.16.20.222
[2] => 10.10.10.100
[3] => 445 , 23
)
[1] => Array
(
[0] => S02 , S03 , S07
[1] => 10.10.10.10
[2] => 192.168.100.100
[3] => 22
)
[3] => Array
(
[0] => S05 , S06
[1] => 100.100.100.100 , 192.168.200.10
[2] => 192.168.100.100
[3] => 22
)
[4] => Array
(
[0] => S08
[1] => 192.168.100.100
[2] => 10.10.100.106
[3] => 446
)
[5] => Array
(
[0] => S09
[1] => 172.16.20.223
[2] => 10.10.10.108
[3] => 447
)
[6] => Array
(
[0] => S10
[1] => 192.168.100.100
[2] => 10.10.10.109
[3] => 448
)
)
Try this:
<?php
$array = array(
array(
'name' => 'filter_amount',
'value' => '100-ml'
),
array(
'name' => 'filter_amount',
'value' => '200-ml'
),
array(
'name' => 'page_size',
'value' => '7'
)
);
$tmp = array();
foreach($array as $val) {
$tmp[$val['name']]['values'][] = $val['value'];
}
foreach($tmp as $k => $v) {
$item = implode(',', array_unique(explode(',', implode(',',$v['values']))));
$newArr[] = array('name' => $k, 'value' => $item);
}
echo '<pre>';
print_r($newArr);
echo '</pre>';
got it with the following crazy mess:
$name = array_column($array, 'name');
$value = array_column($array, 'value');
foreach($name as $nk=>$nv)
foreach($value as $vk=>$vv)
if($nk == $vk)
$a[$nv][] = $vv;
foreach($a as $k=>$v)
$b[$k] = implode(',', $v);
$z = 0;
foreach($b as $k=>$v)
{
$c[$z]['name'] = $k;
$c[$z]['value'] = $v;
$z++;
}
$c is the resulting array
Or using a medley of array functions:
<?php
$array = array(
array(
'name' => 'filter_amount',
'value' => '100-ml'
),
array(
'name' => 'filter_amount',
'value' => '200-ml'
),
array(
'name' => 'page_size',
'value' => '7'
)
);
$names = array_column($array, 'name');
$values = array_column($array, 'value');
$result = [];
foreach (array_unique($names) as $k)
$result[$k] = implode(", ", array_filter($values,
function($v, $indx) use ($names, $k) {
return $names[$indx] == $k;
}, ARRAY_FILTER_USE_BOTH));
print_r($result);
$result2 = [];
foreach ($result as $k=>$v) $result2[] = ['name'=>$k, 'value'=>$v];
print_r($result2);
Results in:
Array
(
[filter_amount] => 100-ml, 200-ml
[page_size] => 7
)
Array
(
[0] => Array
(
[name] => filter_amount
[value] => 100-ml, 200-ml
)
[1] => Array
(
[name] => page_size
[value] => 7
)
)
All of the other answers up to now are using two or more iterating techniques for this task. There only needs to be one loop.
Build an associative output array based on the name values as you iterate. If the associative key isn't set, then save the whole row. If it is set, then just append a comma then the new value data to the stored value element.
Using temporary keys allows isset() to swiftly check for existence. It will always outperform array_search() and in_array() because of how php treats arrays (as hash maps).
Remove the temporary keys when the loop is finished by calling array_values().
Code: (Demo)
$result = [];
foreach ($array as $row) {
if (!isset($result[$row['name']])) {
$result[$row['name']] = $row;
} else {
$result[$row['name']]['value'] .= ',' . $row['value'];
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'name' => 'filter_amount',
'value' => '100-ml,200-ml',
),
1 =>
array (
'name' => 'page_size',
'value' => '7',
),
)

transform array data using php

[original:protected] => Array
(
[user_id] => 65751
[social_id] =>
[parent_id] =>
[org_id] => 1
[type] => 3
[s_id] => 1
[role_id] => 0
[active] => 1
[name] => RX
[first_name] => JJ
[last_name] => DKL
[email] => first#testmail.com
[secondary_email] =>
[username] => cLvcyUr2
)
[1] => User Object
(
[user_id] => 82197
[social_id] =>
[parent_id] =>
[org_id] => 1
[type] => 2
[s_id] => 1
[role_id] => 0
[active] => 1
[name] => sec
[first_name] => XX
[last_name] => J3
[email] => first#testmail.com
[secondary_email] =>
[username] => VfTqXyvJ
)
How to transform the array data mean to keep only two email and username rest should remove
Array (
[0] => Array (
[email] => first#testmail.com
[username] => cLvcyUr2
)
[1] => Array (
[email] => first#testmail.com
[username] => VfTqXyvJ
)
)
How could this possible i do not to unset data one by one it should automatically unset and pick only two value
Did you try something like that :
$index = array_search('user_id', $array);
unset($array[$index]);
Do that for all key you want to remove.
$newArray = [];
foreach ($oldArray as $item) {
$arr = [];
$arr['email'] = $item->email;
$arr['username'] = $item->username;
$newArray[] = $arr;
}
Why not create an empty array and just copy the values you need? Trying to unset everything in your array is a lot of work and is not really maintainable, out of experience.
Note that your pasted code contains both an array and object, but your question is about an array only.
$newArray = [];
foreach ($oldArray as $item) {
$newArray[] = [
'email' => $item->email,
'username' => $item->username
]; // If $item is object
$newArray[] = [
'email' => $item['email'],
'username' => $item['username']
]; // If $item is array
}
var_dump($newArray);

print array values in new format in array

I want to send the value to jquery-variable in new format, i am using nested foreach loop
here is my code:
foreach($names as $key1 => $desc1) {
$arr_names[] = $names;
$details = get_details( $key1 );
if ( is_array( $states ) ) {
foreach($details as $key2 => $desc2) {
$title[] = $key2;
$value[] = $desc2;
}
}
}
echo "<input type='hidden' id='storageElement' data-storectrystts='".json_encode($namdetailsArray)."'>";
Right now, i can get this:
Array
(
[0] => Sam
[1] => Ben
[2] => John
[0] => Age
[1] => Place
[2] => Height
[3] => Weight
[4] => Year
[5] => Salary
[0] => 30
[1] => AU
[2] => 6
[3] => 150
[4] => First
[5] => 50000
)
I need to send value in this format through data-storectrystts='".json_encode($namdetailsArray).":
'Sam' => [
['Age', '30'],
['Place', 'AU']],
'Ben' => [
['Height', '6'],
['Weight', '150']],
'John' => [
['Year', 'First'],
['Salary', '50000']]
Update
//if we use print_r($namdetailsArray); then everything is fine
Array
(
[Sam] => Array
(
[0] => Array
(
[0] => Age
[1] => 30
)
[1] => Array
(
[0] => Place
[1] => AU
)
)
[Ben] => Array
(
[0] => Array
(
[0] => Height
[1] => 6
)
[1] => Array
(
[0] => Weight
[1] => 150
)
)
[John] => Array
(
[0] => Array
(
[0] => Year
[1] => First
)
[1] => Array
(
[0] => Salary
[1] => 50000
)
)
[Derek] => Array
(
[0] => Array
(
[0] => tax's cal
[1] => 100
)
[1] => Array
(
[0] => distance
[1] => 5
)
)
)
//if we use echo json_encode($namdetailsArray) then everything is fine
{"Sam" => [
["Age", "30"],
["Place", "AU"]],
"Ben" => [
["Height", "6"],
["Weight", "150"]],
"John" => [
["Year", "First"],
["Salary", "50000"]],
"Derek" => [
["tax's cal", "100"],
["distance", "5"]]}
/*but if we use
echo "<input type='hidden' id='storageElement' data-storectrystts='".json_encode($namdetailsArray)."'>";
echo '<div id="availhai"></div>';
var cSttArry = $("#storageElement").data('storectrystts');
$("#availhai").html(cSttArry);
then it is not showing anything after word "tax" */
{"Sam" => [
["Age", "30"],
["Place", "AU"]],
"Ben" => [
["Height", "6"],
["Weight", "150"]],
"John" => [
["Year", "First"],
["Salary", "50000"]],
"Derek" => [
["tax
You shouldn't be creating lots of separate arrays. Create a single associative array where the key is the name, and the value is a 2-dimensional array like you show.
$namdetailsArray = array();
foreach ($names as $name => $desc) {
$personArray = array();
foreach ($desc as $key => $value) {
$personArray[] = array($key, $value);
}
$namdetailsArray[$name] = $personArray;
}

how can i count an element if it appears more than once in the same array?

how can i count an element if it appears more than once in the same array?
I already tried with array_count_values, but it did not work, is it beacuse i got more than one key and value in my array?
This is my output from my array (restlist)
Array (
[0] => Array ( [restaurant_id] => 47523 [title] => cafe blabla)
[1] => Array ( [restaurant_id] => 32144 [title] => test5)
[2] => Array ( [restaurant_id] => 42154 [title] => blabla2 )
[3] => Array ( [restaurant_id] => 32144 [title] => test5)
[4] => Array ( [restaurant_id] => 42154 [title] => blabla2 )
)
I want it to count how many times the same element appears in my array and then add the counted value to my newly created 'key' called hits in the same array.
Array (
[0] => Array ( [restaurant_id] => 47523 [title] => cafe blabla [hits] => 1)
[1] => Array ( [restaurant_id] => 32144 [title] => test5 [hits] => 2)
[2] => Array ( [restaurant_id] => 42154 [title] => blabla2 [hits] => 2)
)
This is how i tried to do what i wanted.
foreach ($cooltransactions as $key)
{
$tempArrayOverRestaurants[]= $key['restaurant_id'];
}
$wordsRestaruants = array_count_values($tempArrayOverRestaurants);
arsort($wordsRestaruants);
foreach ($wordsRestaruants as $key1 => $value1)
{
$temprestaurantswithhits[] = array(
'restaurant_id' => $key1,
'hits' => $value1);
}
foreach ($restlistas $key)
{
foreach ($temprestaurantswithhits as $key1)
{
if($key['restaurant_id'] === $key1['restaurant_id'])
{
$nyspisestedsliste[] = array(
'restaurant_id' => $key['restaurant_id'],
'title' => $key['title'],
'hits' => $key1['hits']);
}
}
}
I know this is probably a noob way to do what i want but i am still new at php..I hope you can help
Just try with associative array:
$input = array( /* your input data*/ );
$output = array();
foreach ( $input as $item ) {
$id = $item['restaurant_id'];
if ( !isset($output[$id]) ) {
$output[$id] = $item;
$output[$id]['hits'] = 1;
} else {
$output[$id]['hits']++;
}
}
And if you want to reset keys, do:
$outputWithoutKeys = array_values($output);

Categories