Delete array child where value = somevalue in multidimentional array - php

I have a multidimentional array like this $membergroups :
Array ( [0] =>
Array ( [id] => 1645819602
[name] => Oryza NurFa
[first_name] => Oryza
[last_name] => NurFa
[work] => MAN 2 Yogyakarta )
[1] =>
Array ( [id] => 100000251643877
[name] => Lathif Pambudi
[first_name] => Muhammad Lathif
[last_name] => Pambudi
[work] => Omah TI )
[2] =>
Array ( [id] => 1152078197
[name] => Novantio Bangun
[first_name] => Novantio
[last_name] => Bangun
[work] => Pertamina))
How to delete one of child array with specific value. For the example, I want to delete an array with [id] => 100000251643877 inside? So the output will be :
Array ( [0] =>
Array ( [id] => 1645819602
[name] => Oryza NurFa
[first_name] => Oryza
[last_name] => NurFa
[work] => MAN 2 Yogyakarta )
[1] =>
Array ( [id] => 1152078197
[name] => Novantio Bangun
[first_name] => Novantio
[last_name] => Bangun
[work] => Pertamina))
Here is my php code, but it doesn't work :
if (($key = array_search($user_fbid, $membergroups)) !== false) {
unset($membergroups[$key]);
}
Any help would be greatly appreciated. Thank you

You can make use of array_column but only for php >= 5.5
if (($key = array_search($user_fbid, array_column( $membergroups, 'id') ) !== false) {
unset($membergroups[$key]);
}
array_column( $membergroups, 'id') search in membergroup multidimensional array for id column, and return tou you an array containing all rows values entries with id key.
array_column -> MANUAL

Using a foreach you can do the job like this
$id = 100000251643877;//Example
foreach($membergroups as $key => $value){
if($value['id'] == $id){
unset($membergroups[$key]);
}
}

Loop through the whole array:
foreach ($membergroups as $idx => $group) {
if ($group['id'] === $user_fbid) {
unset($membergrouops[$idx]);
break;
}
}

foreach($membergroups as $key => $value){
if($value['id'] == $user_fbid){
unset($membergroups[$key]);
}
}
Don't forget to merge the array after removing key to keep the index sequantially
$membergroups = array_merge($membergroups);

Related

How to combine array value with same key?

So i have this array that i get from query. The array look like this when i print_r
Array
(
[0] => Array
(
[Name] => NAME 1
[Last] => LastValue1
[Bid] =>
[Ask] =>
)
[1] => Array
(
[Name] => NAME 1
[Last] =>
[Bid] => BidValue1
[Ask] =>
)
[2] => Array
(
[Name] => Name 2
[Last] => LastValue2
[Bid] => BidValue2
[Ask] =>
)
[3] => Array
(
[Name] => NAME 1
[Last] =>
[Bid] =>
[Ask] => AskValue1
)
[4] => Array
(
[Name] =>Name 2
[Last] =>
[Bid] =>
[Ask] => AskValue2
)
)
and i want to achieve array looks like this
Array
(
[0] => Array
(
[Name] => NAME 1
[Last] => LastValue1
[Bid] => BidValue1
[Ask] => AskValue1
)
[2] => Array
(
[Name] => Name 2
[Last] => LastValue2
[Bid] => BidValue2
[Ask] => AskValue2
)
)
I try this way (get it from google)
$result = array();
foreach ($newArray as $element) {
$result[$element['Name']][] = $element;
}
echo "<pre>";print_r($result);
But it is not showing the result that i want. How can i achieve it ?
thanks in advance and sorry for my english
You can use below snippet for the same,
$result = [];
foreach ($newArray as $element) {
foreach ($element as $key => $value) {
// checking if value for key is already added to result array
if ((!empty($result[$element['Name']]) && !array_key_exists($key, $result[$element['Name']])) || empty($result[$element['Name']])) {
if (!empty($value)) { // checking if value not empty
$result[$element['Name']] = ($result[$element['Name']] ?? []);
// merge it to group wise name result array
$result[$element['Name']] = array_merge($result[$element['Name']], [$key => $value]);
}
}
}
}
array_merge — Merge one or more arrays
array_key_exists — Checks if the given key or index exists in the array
Demo
Output:-
Array
(
[0] => Array
(
[Name] => NAME1
[Last] => LastValue1
[Bid] => BidValue1
[Ask] => AskValue1
)
[1] => Array
(
[Name] => Name2
[Last] => LastValue2
[Bid] => BidValue2
[Ask] => AskValue2
)
)
Here is the shortest and simple solution by using foreach with array_filter
foreach($a as &$v){
$v = array_filter($v);
isset($r[$v['Name']]) ? ($r[$v['Name']] += $v) : ($r[$v['Name']] = $v);
}
You can use array_values to re arrange the order of array.
Working example : https://3v4l.org/XeQHa

php add some value on specific location in multidimensional array

I have array like this
Array ([0] => Array ( [user_id] => 21 [email] => momod#modara.com [brand] => Array ( [0] => GOFUEL_W [1] => GOFUEL_USD_W ) ) [1] => Array ( [user_id] => 22 [email] => hemisphere#modara.com [brand] => Array ( [0] => GOFUEL_W ) ) [2] => Array ( [user_id] => 23 [email] => madoka#modara.com [brand] => Array ( [0] => GOFUEL_W [1] => GOFUEL_USD_W [2] => GOFUEL_BGD_W ) ) )
i want to locate user_id 22 and put this value "GO_FUEL_SGD_W" on brand, what should i do, so the view of array will look like this
Array ([0] => Array ( [user_id] => 21 [email] => momod#modara.com [brand] => Array ( [0] => GOFUEL_W [1] => GOFUEL_USD_W ) ) [1] => Array ( [user_id] => 22 [email] => hemisphere#modara.com [brand] => Array ( [0] => GOFUEL_W => [1] =>GO_FUEL_SGD_W ) ) [2] => Array ( [user_id] => 23 [email] => madoka#modara.com [brand] => Array ( [0] => GOFUEL_W [1] => GOFUEL_USD_W [2] => GOFUEL_BGD_W ) ) )
Just use loop:
foreach($array as &$item)
{
if(array_key_exists('user_id', $item) &&
$item['user_id']==22 &&
array_key_exists('brand', $item) &&
!in_array('GO_FUEL_SGD_W', $item['brand']))
{
$item['brand'][] = 'GO_FUEL_SGD_W';
}
}
A simple foreach loop will do the job:
foreach($myarray AS &$subarray) {
if($subarray['user_id'] == 22) {
$subarray['brand'][] = "GO_FUEL_SGD_W";
break;
}
}
Working example: http://3v4l.org/8aQMj
You will need to iterate over the array and look for the element you're searching for.
foreach ($array as &$element) {
if ($element['user_id'] != 22)
continue;
$element['brand'][] = "GO_FUEL_SGD_W";
break;
}
With continue; all elements will be skipped, who have $element['user_id'] != 22 (and so none of the code after the continue; will be applied to them!).
Also it will end the loop once the requested element is reached and modified, thanks to break;.
$array= //your array;
foreach($array as $x){
if($x['user_id']=='22'){
$x['brand'][]='GO_FUEL_SGD_W';
break;
}
}

PHP Multidimensional sort?

I have a rather annoying array structure to work with and I need to sort it by any arbitrary key combination. 2 records are displayed below but multiple records with or without the same structure will be present when sorting is actioned.
Here are two records.
Array(
[0] => Array
(
[cid] => 1
[title] => Mr
[first_name] => Abet
[last_name] => Simbad
[emails] => Array
(
[374] => Array
(
[eid] => 374
[name] => ski lodge
[email] => simbad#skifree.com
)
[373] => Array
(
[eid] => 373
[name] => work
[email] => simbad#work.com
)
[375] => Array
(
[eid] => 375
[name] => personal
[email] => simbad#gmail.com
)
)
)
[1] => Array
(
[cid] => 2
[title] => Mrs
[first_name] => Angie
[last_name] => Stokes
[emails] => Array
(
[590] => Array
(
[eid] => 590
[name] => work
[email] => angie#gmail.com
)
)
)
So if I wanted to sort by email in ascending order in the emails array, how can I get the second complete record to come first in the result array? angie#gmail.com comes before simbad#....
Also Some records will not contain an emails array. They would be last in the result set.
Any help would be much appreciated.
The array shown is a cut down version but I have addresses, notes, phones and websites in the same annoying structure. Ideally I could sort with something like
$sort = array('emails','email')
$data = sort_data_func('ASC',$sort,$data);
But anything steps in the right direction will help. :)
Here's some code I have so far
$sort = array('emails','email');
foreach($contacts as $ckey => $c){
if(is_array($c[$sort[0]])){
foreach($c[$sort[0]] as $key1 => $sort0){
if($sort0[$sort[1]]!=''){
$res[$sort[0]][$ckey][$sort[1]][] = $sort0[$sort[1]];
}
}
}
}
print_r($res);
Which produces:
Array
(
[emails] => Array
(
[0] => Array
(
[0] => simbad#skifree.com
[1] => simbad#work.com
[2] => simbad#gmail.com
)
[1] => Array
(
[0] => angie#gmail.com
)
)
)
But I have no idea where to go from here.
EDIT
OK I have the records in the currect order now but how can I keep the initial record ID in the resulting array?
Here's what I'm using.
$direction=='ASC'
function cmp_asc($a, $b){
$key = current(array_keys($a));
sort($a[$key]);
$a[$key] = current($a[$key]);
sort($b[$key]);
$b[$key] = current($b[$key]);
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
function cmp_desc($a, $b){
$key = current(array_keys($a));
asort($a[$key]);
$a[$key] = current($a[$key]);
asort($b[$key]);
$b[$key] = current($b[$key]);
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
if($direction=='ASC'){
usort($res[$sort[0]], 'cmp_asc');
}else{
usort($res[$sort[0]], 'cmp_desc');
}
In
Array
(
[emails] => Array
(
[0] => Array
(
[email] => Array
(
[0] => simbad#skifree.com
[1] => simbad#work.com
[2] => simbad#gmail.com
)
)
[1] => Array
(
[email] => Array
(
[0] => angie#gmail.com
)
)
)
)
Out
Array
(
[emails] => Array
(
[0] => Array
(
[email] => Array
(
[0] => angie#gmnail.com
)
)
[1] => Array
(
[email] => Array
(
[0] => simbad#skifree.com
[1] => simbad#work.com
[2] => simbad#gmail.com
)
)
)
)
One of the usort functions, combined with a self-written comparison function that detects the order in which two elements should be sorted, should do the trick.

Get values (plural) from multi-dimensional array with key

I know the key, now I need ALL of the results that would yield when I search the 5000+ user database. Any user may have none, one or multiple locations, identified by an id and name field. Therefore I need the results in an array, not just the first/last one, but all of them. Below is an example of a user (actual array setup, fake data ;) )
Array
(
[ID] => 2
[user_login] => SomeGuy
[user_pass] => GreatEncryptedPassword
[user_nicename] => Some Guy
[user_email] => someguy#has-email.com
[user_url] => someguy.com
[user_registered] => 2013-04-11 11:18:58
[user_activation_key] =>
[user_status] => 0
[display_name] => Some Guy
[umeta_id] => 31
[user_id] => 2
[meta_key] => facebookmeta
[meta_value] => Array
(
[id] => 1234567890
[name] => Some Guy
[first_name] => Some
[last_name] => Guy
[link] => http://www.facebook.com/someguy
[username] => someguy
[birthday] => 02/21/1983
[location] => Array
(
[id] => 108276092536515 //actual ID, try at facebook.com/108276092536515
[name] => Arnhem, Netherlands
)
[gender] => male
[relationship_status] => In a Relationship
[significant_other] => Array
(
[name] => Some Chick
[id] => 12345678906789
)
[email] => someguy#has-email.com
[timezone] => 2
[locale] => nl_NL
[verified] => 1
[updated_time] => 2013-04-02T09:28:30+0000
)
)
As you can make out, this guy has 1 location in his facebook data, but other locations include the same [location] => Array ( [id] => 123 [name] => SomePlace ) for example for [work] or [education], or, or, or...
I've tried a recursive function like this:
function get_value_by_key( $array, $key ){
foreach( $array as $k => $each ){
if( $k == $key ){
return $each;
}
if( is_array( $each )){
if( $return = get_value_by_key($each,$key)){
return $return;
}
}
}
}
print_r( get_value_by_key( $users, 'location' );
How can I modify the above function to return an array of location arrays? This one return the above data of the first user containing a location, not the location itself or an array of them.
EDIT:
What I need as a result is something like this:
Array(
[0] => Array(
[id] => 1234567890
[name] => GreatCity, World
)
[1] => Array(
[id] => 2345678901
[name] => SomeCity, Blop
)
[2] => Array(
[id] => 3456789012
[name] => AnotherCity, Boo
)
)
Edit based on answer
Answer from Thomas David Plat gives me the correct results, but still a not very usable data structure. How to get the results out of the structure and into that shown in the above edit?
Results from David's answer:
Array
(
[0] => Array
(
[0] => Array
(
[0] => Array
(
[id] => 108276092536515
[name] => Arnhem, Netherlands
)
[1] => Array()
)
)
[1] => Array
(
[0] => Array
(
[0] => Array
(
[id] => 108276092536515
[name] => Arnhem, Netherlands
)
[1] => Array()
)
)
[2] => Array()
[3] => Array()
[4] => Array()
I've tried variations of array_filter, array_map, array_values and others like below:
$locations = array_map( 'array_filter', find_array_values( $users, 'location' ));
But the structure seems to stay...
UPDATED ANSWER
$matches = array();
function find_array_values($haystack, $needle)
{
global $matches;
$collection = array();
foreach($haystack AS $key => $value)
{
if($key === $needle)
{
$matches[] = $value;
}
else if(is_array($value))
{
find_array_values($value, $needle);
}
}
}
find_array_values($array, 'location');
print_r($matches);
?>
This will work, but as I already said in the comments it's a bad practice since it uses the global keyword. If you implement this function as a method into a class, instead of using the global keyword you could use a class variable which would be a neat solution.
OLD Answer
function find_array_values($haystack, $needle)
{
$collection = array();
foreach($haystack AS $key => $value)
{
if($key === $needle)
{
$collection[] = $value;
}
else if(is_array($value))
{
$collection[] = find_array_values($value, $needle);
}
}
return $collection;
}
echo "<pre>";
print_r(find_array_values($users, 'location'));
echo "</pre>";
Here you are. Just pass an array of your users into the function. The function will return an array of arrays of locations.
There's one restriction. The function will not search trough locations that are within locations.
you can modify ur location part of your array like this
[location] => Array
(
[work]=> Array(
[id] => 108276092536515
[name] => Arnhem, Netherlands
)
[home] => Array(
[id] => 108276092536515
[name] => Arnhem, Somewhere else
)
)
if you modify your array like this then your function will return array of arrays for location

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