I need your help the problem description is given
The array is as follows
The given array is the sample. The main array contains many entries as follow where username can differ.
Case 1:
$my_array = Array
(
0 => Array
(
'username' => Pete,
'userid' => 1,
'option'=>no
),
1 => Array
(
'username' => Pete,
'userid' => 2,
'option'=>yes
),
2 => Array
(
'username' => John,
'userid' => 1,
'option'=>no
)
3 => Array
(
'username' => John,
'userid' => 1,
'option'=>yes
)
) ;
Case 2:
$my_array = Array
(
0 => Array
(
'username' => Pete,
'userid' => 2,
'option'=>yes
),
1 => Array
(
'username' => Pete,
'userid' => 1,
'option'=>no
),
2 => Array
(
'username' => John,
'userid' => 1,
'option'=>no
)
3 => Array
(
'username' => John,
'userid' => 1,
'option'=>yes
)
) ;
I want to delete the element where 'username'=>Pete and 'Option'=>no
So the output should be looks like
Array
(
[0] => Array
(
[username] => Pete
[userid] => 2
[option] => yes
)
[2] => Array
(
[username] => John
[userid] => 1
[option] => yes
)
)
All element of sub array can be same but option field either yes or no.
Please help me
Thank you very much in advance
this can be a solution
$result = array();
foreach ($yourArray as $key => $value) {
if(!($value['username']=="Pete" && $value['options']=="no"))
array_push($result, $value);
}
With this code you can achieve that:
foreach($my_array as $key => $value){
if($value['username'] == 'Pete' && $value['option'] == 'yes'){
unset($my_array[$key]);
}
}
Use a foreach loop! If the current value for username = pete add a variable user=true;
Then after that check if(option == no){ if(user==true){ DELETE ROW } }
You can use array_filter
>>> array_filter($my_array,
function($obj){
return $obj["option"] !== "no" || $obj["username"] !== "Pete";
}
)
=> [
1 => [
"username" => "Pete",
"userid" => 2,
"option" => "yes"
],
2 => [
"username" => "John",
"userid" => 1,
"option" => "no"
]
]
As the function name suggests, you should use array_filter()
$my_array = array_filter($my_array, function($v){
return ($v['username'] != 'Pete' && $v['option'] != 'no');
});
Related
I want to remove key 0 from parent array and set child array as parent.
Here I will get single value so one array is ok for me.
My current array looks like this
Array
(
[0] => Array
(
[id] => 3
[api_key] => acount266
[auth_domain] => Tester26
[database_url] => vcc.test.acc+27#gmail.com
[project_id] => 12345
[storage_bucket] =>
[secret_key_path] =>
[fcm_server_key] => 1
[messaging_sender_id] => 0
[key_phrase] =>
[disable] => 0
[created] =>
[updated] =>
)
)
I want it like below. expected result
Array
(
[id] => 3
[api_key] => acount266
[auth_domain] => Tester26
[database_url] => vcc.test.acc+27#gmail.com
[project_id] => 12345
[storage_bucket] =>
[secret_key_path] =>
[fcm_server_key] => 1
[messaging_sender_id] => 0
[key_phrase] =>
[disable] => 0
[created] =>
[updated] =>
)
For this I tried like below but no success.
$new = array();
foreach ($data as $v){
$new = array_merge($new , array_values($v)) ;
}
but in my code it's removed key e.g id,api_key, etc....
I need key name also in my new array. please suggest
Remove the array_values
Solution
<?php
$test = array(
array
(
'id' => 3,
'api_key' => 'acount266'
)
);
$new = array();
foreach($test as $v){
$new = array_merge($new, $v);
}
var_dump($new);
Result
array(2) {
["id"]=>
int(3)
["api_key"]=>
string(9) "acount266"
}
According to documentation of PHP as mentioned
reset() function returns the value of the first array element, or
FALSE if the array is empty.
$array = array(
array(
'id' => 3,
'api_key' => 'acount266',
'auth_domain' => 'Tester26',
'database_url' => 'vcc.test.acc+27#gmail.com',
'project_id' => '12345',
'storage_bucket' => '',
'secret_key_path' => '',
'fcm_server_key' => 1,
'messaging_sender_id' => 0,
'key_phrase' => '',
'disable' => 0,
'created' => '',
'updated' => ''
)
);
print_r(reset($test));
I tried this:
$arr = array();
foreach ($examples as $example) {
foreach ($example as $e) {
array_push($arr, $e);
}
}
Don't overcomplicate this, reassigning the first element to the parent array is quick and easy:
<?php
$array =
array (
0 =>
array (
'first' => 'Michael',
'last' => 'Thompson'
)
);
$array = $array[0];
var_export($array);
Output:
array (
'first' => 'Michael',
'last' => 'Thompson',
)
Or:
$array = array_shift($array);
I am trying to search this array by the value of ['field'] and then return the value of ['value'] associated with that field in the array.
For example, I want to say "Tell me the value associated with theThirdField".
I've tried many, many permutations of something like the following:
$myVariable = $Array['result']['totalrows'][0]['rownum'][0]['field'];
To further clarify, I will never know which order / sub-array my search field is located in, I only know the string value associated with ['field'].
How would I accomplish this?
Array
(
[result] => Array
(
[totalrows] => 1
[rows] => Array
(
[0] => Array
(
[rownum] => 1
[values] => Array
(
[0] => Array
(
[field] => testMeOnce
[value] => 436586498
)
[1] => Array
(
[field] => testMeTwice
[value] => 327698034
)
[2] => Array
(
[field] => theThirdField
[value] => 108760374
)
[3] => Array
(
[field] => theFourthField
[value] => 2458505
)
[4] => Array
(
[field] => fifthField
[value] => -0.0201
)
)
)
)
)
)
Did you expect something like that?
$needle = 'theThirdField'; // searched field name
$valuesArray = $Array['result']['rows'][0]['values']; //now you have clearer array
array_walk($valuesArray, function($element, $key) use ($needle) {
if ($element['field'] == $needle) {
echo $element['value'];
}
});
I would do something like this, assuming you want to search only in the $myVariable dimension :
$myVariable = $Array['result']['rows'][0]['values'];
foreach ($myVariable as $key => $value) {
if( $value['field'] === 'theThirdField' ) {
echo $value['value'];
break;
}
}
when I ran your code, I got some syntax errors. I have changed your Array to this (changed syntax only):
$a = Array
(
'result' =>
[
'totalrows' => 1,
'rows' =>
[
0 =>
[
'rownum' => 1,
'values' =>
[
0 =>
[
'field' => 'testMeOnce',
'value' => 436586498
],
1 =>
[
'field' => 'testMeTwice',
'value' => 327698034
],
2 =>
[
'field' => 'theThirdField',
'value' => 108760374
],
3 =>
[
'field' => 'theFourthField',
'value' => 2458505
],
4 =>
[
'field' => 'fifthField',
'value' => -0.0201
]
]
]
]
]
);
now you can get the value like this:
print($a['result']['rows'][0]['values'][2]['value']); // --> 108760374
I hope that this is what you are looking for!
Thanks everyone. I used a mix of your suggestions and ended up doing the following:
$valuesArray = $Array['result']['rows'][0]['values'];
foreach ($valuesArray as $value) {
$fieldName = $value['field'];
$$fieldName = $value['value'];
}
Since I know the names of all the fields I want, but not the order, this allowed me to capture all of the values of each field with the name of the field becoming the variable name.
I am comparing three value in an array and i am getting all value.
How can i output specific value or value that i only want to output
Because i want to output value that i only nedeed.
I have this code:
<?php
$participants = [
[ 'calleridnum' => 1,
'callee' => 'yay'
],
[ 'calleridnum' => 2,
'callee' => 'yay'
],
[ 'calleridnum' => 3,
'callee' => 'yay'
]
];
$conferance_participants = [
[ 'uid' => 1,
'caller' => 'yay2',
'dit' => 'deze'
],
[ 'uid' => 2,
'caller' => 'test',
'dit' => 'wew'
]
];
$contacts = [
[ 'name' => 1,
'test' => 'yay2',
'limit' => 1
],
[ 'name' => 2,
'test' => 'yay2',
'limit' => 1
]
];
foreach ($participants as $participant=>$p) {
foreach ($conferance_participants as $conferance_participant=>$cp) {
foreach ($contacts as $contact=>$cs) {
if (($p['calleridnum'] == $cp['uid']) && ($cp['uid'] == $cs['name'])){
$conferance_participants[$conferance_participant] = array_merge(
$participants[$participant],
$conferance_participants[$conferance_participant],
$contacts[$contact]
);
}
}
}
}
echo "<pre>";
print_r($conferance_participants);
echo "</pre>";
?>
and my output is:
Array
(
[0] => Array
(
[calleridnum] => 1
[callee] => yay
[uid] => 1
[caller] => yay2
[dit] => deze
[name] => 1
[test] => yay2
[limit] => 1
)
[1] => Array
(
[calleridnum] => 2
[callee] => yay
[uid] => 2
[caller] => test
[dit] => wew
[name] => 2
[test] => yay2
[limit] => 1
)
)
I want ot minimize my output.
I want to remove name test from the $contacts array
I also want to remove caller dit from the $conferance_participants array
so that my output will be :
Array
(
[0] => Array
(
[calleridnum] => 1
[callee] => yay
[uid] => 1
[limit] => 1
)
[1] => Array
(
[calleridnum] => 2
[callee] => yay
[uid] => 2
[limit] => 1
)
)
Your code is hard to understand,
Number of times your foreach will execute,
count($participants) * count($conferance_participants) * count($contacts);
Number of times this code's foreach will execute will be equal or less than your codes, because it will stop as soon as the match found.
Also i have created a new function, for searching in another arrays, so it will make the next person working on this code less bang his head on the desk.
Passes $conferance_participants variable's value as reference, note the & in foreach declaration so no need to worry about keys of the array.
foreach($conferance_participants as &$record) {
# find keys of corresponding array matches
$key_in_participants = _custom_search($record['uid'], $participants, 'calleridnum');
$key_in_contacts = _custom_search($record['uid'], $contacts, 'name');
# unset unwanted things
unset($record['caller'], $record['dit']);
# activate this code if you want to make false for unmatched records
/* ***********************************************************************
if($key_in_participants === false || $key_in_contacts === false) {
$record['calleridnum'] = $record['callee'] = $record['limit'] = false;
continue;
}
*********************************************************************** */
# setting required things
$record['calleridnum'] = $participants[$key_in_participants]['calleridnum'];
$record['callee'] = $participants[$key_in_participants]['callee'];
$record['limit'] = $contacts[$key_in_contacts]['limit'];
}
function _custom_search($id, $array, $key_to_search) {
foreach ($array as $key => $val) if($val[$key_to_search] === $id) return $key;
return false;
}
This will make $conferance_participants exactly as you want.
You can just unset the array keys before you merge the arrays. Then set the 'name' key again for $contacts array which is needed for the loops above.
Here is the modified code sample:
<?php
$participants = [
[ 'calleridnum' => 1,
'callee' => 'yay'
],
[ 'calleridnum' => 2,
'callee' => 'yay'
],
[ 'calleridnum' => 3,
'callee' => 'yay'
]
];
$conferance_participants = [
[ 'uid' => 1,
'caller' => 'yay2',
'dit' => 'deze'
],
[ 'uid' => 2,
'caller' => 'test',
'dit' => 'wew'
]
];
$contacts = [
[ 'name' => 1,
'test' => 'yay2',
'limit' => 1
],
[ 'name' => 2,
'test' => 'yay2',
'limit' => 1
]
];
foreach ($participants as $participant=>$p) {
foreach ($conferance_participants as $conferance_participant=>$cp) {
foreach ($contacts as $contact=>$cs) {
if (($p['calleridnum'] == $cp['uid']) && ($cp['uid'] == $cs['name'])){
unset($contacts[$contact]['name'], $contacts[$contact]['test']);
unset($conferance_participants[$conferance_participant]['caller'], $conferance_participants[$conferance_participant]['dit']);
$conferance_participants[$conferance_participant] = array_merge(
$participants[$participant],
$conferance_participants[$conferance_participant],
$contacts[$contact]
);
$contacts[$contact]['name'] = $cs['name'];
}
}
}
}
echo "<pre>";
print_r($conferance_participants);
echo "</pre>";
The output you should get:
Array
(
[0] => Array
(
[calleridnum] => 1
[callee] => yay
[uid] => 1
[limit] => 1
)
[1] => Array
(
[calleridnum] => 2
[callee] => yay
[uid] => 2
[limit] => 1
)
)
I hope that answers your question. Thanks.
After merging, you may filter only certain keys you want to be present in final result using array_intersect_key().
$keys = array_flip(['calleridnum', 'callee', 'uid', 'limit']);
$conferance_participants[$conferance_participant] =
array_intersect_key(
array_merge(
$participants[$participant],
$conferance_participants[$conferance_participant],
$contacts[$contact]
),
$keys
);
I have to array and I want to merge this two array with a main key ( ID ) , and I would like to order alphabetically this NEW array ( the lastname field )
Array (
[0] =>
Array ( [id] => 172
[user_id] => 1217330
[behaviour_action_id] => 97
[state] => accepted
)
[1] =>
Array (
[id] => 173
[user_id] => 1217330
[behaviour_action_id] => 97
[state] => pending
) )
And this array
Array (
[1217330 ] =>
Array ( [firstname] => Philip
[lastname] => Audet
[birthdate] => 1995-07-17
[id] => 1217330
)
[232323] =>
Array ( [firstname] => Frédéric
[lastname] => Bouchard-Dubé
[birthdate] => 1995-07-17
[id] => 232323
)
And I would like to have this
[0] =>
Array ( [id] => 172
[user_id] => 1217330
[behaviour_action_id] => 97
[state] => accepted
[firstname] => Philip
[lastname] => Audet
)
[1] =>
Array (
[id] => 173
[user_id] => 1217330
[behaviour_action_id] => 97
[state] => pending
[firstname] => Philip
[lastname] => Audet
) )
I wont want to have the birthdate index for THIS array, I only want to get the firstname and the lastname from the second array. So I want to math the index USER_ID ( first_table) with ID (second table). I also want to order this new table alphabetically with the lastname (in my exemple, I don't need to sort it alphabetically, but I will need to do this )
Can some one can help me please ? Thx
Thx
This is doing what you are looking for. As your example is out of context you might need to take some different approaches, but I hope it will help you get the task done.
$behaviour = array(
array(
'id' => 172,
'user_id' => 1217330,
'behaviour_action_id' => 97,
'state' => 'accepted'
),
array(
'id' => 173,
'user_id' => 232323,
'behaviour_action_id' => 97,
'state' => 'pending'
),
);
$users = array(
1217330 => array(
'firstname' => 'Philip',
'lastname' => 'Audet',
'birthdate' => '1995-07-17',
'id' => 1217330
),
232323 => array(
'firstname' => 'Frédéric',
'lastname' => 'Bouchard-Dubé',
'birthdate' => '1995-07-17',
'id' => 232323
),
);
//we will collect the data in a new array
$combined = array();
//now we loop through all behaviours
foreach($behaviour as $key => $behaviourData){
//we look up the data which belongs to the user of this behaviour
$wantedUserData = $users[$behaviourData['user_id']];
//birthdate is unwanted
unset($wantedUserData['birthdate']);
//merge data
$combined[] = array_merge($behaviourData, $wantedUserData);
}
//order array
usort($combined,'cmp');
//voilà!
var_dump($combined);
//Comparison function used in usort above
function cmp($a, $b){
if ($a['lastname'] == $b['lastname']){
return 0;
}
return ($a['lastname'] < $b['lastname']) ? -1 : 1;
}
$arr1 = array (
array("id"=>172, "user_id"=>1217330, "behaviour_action_id"=>97, "state"=>"accepted"),
array("id"=>173, "user_id"=>1217330, "behaviour_action_id"=>97, "state"=>"pending")
);
$arr2 = array(
"1217330" => array(
"firstname" => "Philip",
"lastname" => "Audet",
"birthdate" => "1995-07-17",
"id" => 1217330
),
"232323" => array (
"firstname" => "Frédéric",
"lastname" => "Bouchard-Dubé",
"birthdate" => "1995-07-17",
"id" => 232323
)
);
foreach($arr1 as $arr) {
$extra = $arr2[$arr["user_id"]];
unset($extra["birthdate"]);
$newarray[] = array_merge($extra, $arr);
}
print_r($newarray);
this one? (assuming $arr1 and $arr2 the given arrays)
$arr3 = array();
foreach($arr1 as $key=>$val) {
$arr3[$key] = $val;
$arr3[$key]["firstname"] = $arr2[$val["user_id"]]["firstname"];
$arr3[$key]["lastname"] = $arr2[$val["user_id"]]["lastname"];
}
echo "<pre>";
print_r($arr3);
echo "</pre>";
Well, I don't want to give a cooked-up code but this algorithm will do the job:
1) Loop through first array and create another array with user_id as key. like
$new_array[$array['user_id']] = array($array['id'], $array['state']...);
2) Loop through second array and unset() the key birthdate.
3) Use array_merge_recursive() and merge the two arrays.
I have two arrays:
Array
(
[0] => Array
(
[id] => 1
[type] => field
[remote_name] => Title
[my_name] => title
[default_value] => http%3A%2F%2Ftest.com
)
[1] => Array
(
[id] => 2
[type] => field
[remote_name] => BookType
[my_name] => book-type
[default_value] =>
)
[2] => Array
(
[id] => 3
[type] => value
[remote_name] => dvd-disc
[my_name] => dvd
[default_value] =>
)
)
Array
(
[title] => Test
[book-type] => dvd
)
I need to take each key in the second array, match it with the my_name value in the first array and replace it with the corresponding remote_name value of the first array while preserving the value of the second array.
There's got to be some carrayzy function to help!
EDIT: There will also be a few cases that the value of the second array will need to be replaced by the value of the first array's remote_name where the value of the second array matches the value of the first array's my_name. How can I achieve this?
EG: book-type => dvd should turn into BookType => dvd-disc
Like so?:
$first = array(
array(
'id' => 1,
'type' => 'field',
'remote_name' => 'Title',
'my_name' => 'title',
'default_value' => 'http%3A%2F%2Ftest.com',
),
array(
'id' => 2,
'type' => 'field',
'remote_name' => 'BookType',
'my_name' => 'book-type',
'default_value' => '',
),
array(
'id' => 3,
'type' => 'value',
'remote_name' => 'dvd-disc',
'my_name' => 'dvd',
'default_value' => '',
),
);
$second = array(
'title' => 'Test',
'book-type' => 'dvd',
);
$map = array('fields' => array(), 'values' => array());
foreach ($first as $entry) {
switch ($entry['type']) {
case 'field':
$map['fields'][$entry['my_name']] = $entry['remote_name'];
break;
case 'value':
$map['values'][$entry['my_name']] = $entry['remote_name'];
break;
}
}
$new = array();
foreach ($second as $key => $val) {
$new[isset($map['fields'][$key]) ? $map['fields'][$key] : $key] = isset($map['values'][$val]) ? $map['values'][$val] : $val;
}
print_r($new);
Output:
Array
(
[Title] => Test
[BookType] => dvd-disc
)
Explanation:
The first loop collects the my_name/remote_name pairs for fields and values and makes them more accessible.
Like so:
Array
(
[fields] => Array
(
[title] => Title
[book-type] => BookType
)
[values] => Array
(
[dvd] => dvd-disc
)
)
The second loop will traverse $second and use the key/value pairs therein to populate $new. But while doing so will check for key/value duplicates in $map.
Keys or values not found in the map will be used as is.
foreach($arr1 as &$el) {
$el['remote_name'] = $arr2[$el['my_name']];
}
unset($el);
I am not aware of such a carrayzy function, but I know how you could do it:
//$array1 is first array, $array2 is second array
foreach($array1 as $key => $value){
if (isset($value['remote_name'], $value['my_name']) && $value['remote_name'] && $value['my_name']){
$my_name = $value['my_name'];
if (isset($array2[$my_name])) {
$remote_name = $value['remote_name'];
$array2[$remote_name] = $array2[$my_name];
//cleanup
unset($array2[$my_name]);
}
}
}