Create an Array with a KEY if values exists in two arrays? - php

I am having problem with handling arrays. I want to "compare" two arrays to see if there's matching "usernames" in both arrays. I am not sure if I am using in_array() function properly
this is how my arrays look like:
USER array 1:
Array ( [0] => Array ( [username] => LNDP [station] => D08 )
[1] => Array ( [username] => ACMAN [station] => D06 )
[2] => Array ( [username] => VTER [station] => D13 )
)
//the users will have to be matched with memo_code
$user = array();
while($row = mysqli_fetch_assoc($get_user_result)){
$user[] = array( "username" => $row['username'],
"station" => $row['station_number']
);
}
MEMO array 2:
Array ( [0] => Array ( [username] => VTER[aht_value] => 333 )
[1] => Array ( [username] => ACMAN [aht_value] => 456 )
[2] => Array ( [username] => ACYL [aht_value] => 789 )
)
$memo = array();
while ($row = mysqli_fetch_assoc($dbh2_result)){
$memo[] = array( "username" => $row['memo_code'],
"aht_value" => $row['avg_handle_time']
);
}
I want to check every "username" in my MEMO array to match the "username" in my USER array.
If they do match, I want to create an array with username, station, aht_value like so:
Array ( [0] => Array ( [username] => ACMAN [aht_value] => 456 [station] => D06 )
)
//creating array 3 by comparing 1 and 2 by using key value of "username" from array 2
$result = array();
//$m = key
//$m['username'] = key value
foreach($memo as $m => $m['username']){
//if username in array 2 is in array 1
if( in_array( $m, $user) ){
//if aht_value is not null
if( $memo['aht_value'] != null ){
$result[] = "username: " . $user['username'] . "aht_value: " .$m['aht_value'] . "position: " . $user['position']. "<br>";
}
//else if aht_value is null
else{
$result[] = "username: " . $user['username'] . "aht_value: NA position: " . $user['position'] . "<br>";
}
}
//if there is no matching username do something?
else{
echo "no match";
}
}
$final_result = json_encode($result);
echo $final_result;
error message
Warning: Cannot use a scalar value as an array in line 97 :
foreach($memo as $m => $m['username']){
If I need to clarify things please ask. After successfully creating the third array I will use json_encode to make an AJAX call and use type GET.
Thanks in advance for the help!

instead of downvoting can someone please tell me what would be best to edit
First, people do not need to provide a reason for downvote, even if they did you wouldn't necessarily get anything constructive, just "I disagree" - "the question is poor".
Second, the question is not 100% clear, your code was a little rough around the edges before editing and when you got the downvotes, and is still unclear even after the edits.
You also do not state why your current attempt fails, what it does, what it is supposed to do, etc.
The issues
Your arrays do not seem to have matching keys to be able to pair anything up, especially given they 2nd dimension, trying to access cross section values which have no matching keys is very complicated.
It's not impossible, but given the huge code block required to try to make sense of your data, it's just not practical. A re-think in how you use the data is needed really.
EG
array_1 has keys of "username" and "station", yet your array_2 has keys of "memo_code" and "aht_value. There is no way to correlate from one thing to another using keys because there are no key pairs from one array to another.
When you loop an array, say array_1, you can get a matching value in array_2 from the current loop's value from array_1, but you do not have the index of array_2's value which is matched from array_1, you just have the value, which means you cannot obtain additional data from array_2, as you only have a value match, and not an index.
It's messy, really, especially given your scenario is really not complex enough to warrant such a complex scenario - in fact no scenario should really do the above, as there's nearly always a better "approach" rather than producing such a poor "fix".
Other solution
Why in array_2 is there a key "memo_code" which seems to be "username" from array_1?
It must be as you are wanting to marry up "username" with "memo_code".
So why not have "username" in array_2 as well, if that's what it is?
Going further, again I could be wrong but this is based on the info in your question - why not just have "aht_value" in array_1 and have no array_2?
Maybe there is a need for two arrays, which is not shown in your question, however what I get from your (confusing and a little garbled) question, is this "could" be fine:
$single_array = array
( "0" => Array ( "username" => "LNDP", "station" => "D08", "aht_value" => "whatever")
"1" => Array ( "username" => "ACMAN", "station" => "D06", "aht_value" => "something" )
"2" => Array ( "username" => "VTER", "station" => "D13", "aht_value" => NULL )
);
You can get all values in one go which relate to the one username, even if they are on different tables just do a join (I presume you have foreign keys/relationships between the two tables.
If you need two arrays
If you need to keep both arrays (for whatever reason your scenario demands) and you cannot change this approach, then can you at least change it to have some kind of corresponding index in each array?
You could then can match one index from another, then take data from the matched pair.
Such as your indexes could be the usernames:
$user = array ( "LNDP" => Array ( "station" => "D08" )
"ACMAN" => Array ( "station" => "D06" )
"VTER" => Array ( "station" => "D13" )
);
$memo = array ( "VTER" => Array ( "aht_value" => "" )
"ACMAN" => Array ( "aht_value" => "456" )
"ACYL" => Array ( "aht_value" => "789" )
);
Then loop one of the arrays, and where index (username) matches, you can get the rest of the data from that index easily and append it to a new array.
If you really must do it the way you have asked
Again, it is not impossible, but you'd need a huge block of code which would:
Loop array_1 and get a matching value pair from array_2 from the
current loop's value
Use the identified value from array_2 and access the 2nd array
separately and find the matching value's index
Use the found index to get the additional data required
Append it to the "new" array
Start going through the loop again
Hope some of this helps.

I found the solution after understanding arrays and key values.. these are two possible answer if ever someone wants to do something similar.
answer 1 :
foreach ($memo as $i => $memodata) {
foreach ($user as $j => $userdata) {
if ($memodata['username'] == $userdata['username']) {
if (is_null($memodata['aht_value'])) {
$result[] = "username: " . $userdata['username'] . " aht_value: NA position: " . $userdata['station'];
}
else {
$result[] = "username: " . $userdata['username'] . " aht_value: " .$memodata['aht_value'] . " position: " . $userdata['station'];
}
}
}
answer 2:
foreach ($memo as $username => $memodata) {
if (in_array($username, array_keys($user))) {
// Match username against the keys of $user (the usernames)
$userdata = $user[$username];
if (is_null($memodata['aht_value'])) {
$result[] = array( 'username' => $userdata['username'],
'aht_value' => 'NA',
'station' => $userdata['station']
);
}
else {
$result[] = array( 'username' => $userdata['username'],
'aht_value' => substr($memodata['aht_value'],0,-3),
'station' => $userdata['station']
);
}
}
}

Related

PHP recursive function returning null array

I have a huge array in which keys are also not constant in most of the cases, but there are 3 keys that always constant (#name,#default_value,#value) and #default_value and #value is different i want to get these kind of sub arrays in 1 simple array , for this purpose i am using recursion in whole array and checking out if these 3 keys are present there i can print these values inside recursion easily but I am not able to get those values in return. So that i can precess them further.
$form=array();
$form['field_one']['#name']="field_one";
$form['field_one']['#default_value']="old";
$form['field_one']['#value']="new";
$form['field_two']['#name']="field_two";
$form['field_two']['#default_value']="old";
$form['field_two']['#value']="new";
$form['field_three']['#name']="field_three";
$form['field_three']['#default_value']="old";
$form['field_three']['#value']="old";
$form['thiscouldbeanotherarray']['idk']['field_four']['#name']="field_four";
$form['thiscouldbeanotherarray']['idk']['field_four']['#default_value']="old";
$form['thiscouldbeanotherarray']['idk']['field_four']['#value']="new";
$arr_get = get_updatedvalues($form,array());
var_dump($arr_get);
function get_updatedvalues($form,$fields) {
if (!is_array($form)) {
return;
}
foreach($form as $k => $value) {
if(str_replace('#','',$k) =='default_value' && ($form['#default_value'] != $form['#value'] ) ){
$fields['field'][$form['#name']] = array("name" => $form['#name'],"old_value" =>$form['#default_value'],"new_value" =>$form['#value']);
var_dump($fields);
}
get_updatedvalues($value,$fields);
}
return $fields;
}
If you run this code it will give you $arr_get > array (size=0), there i need all three values
If I understand correctly, you need to pass fields as a reference in order to change it:
function get_updatedvalues($form, &$fields) {
To do that, however, you'll need to change your initial call so that you have a variable to pass as the reference:
$array = [];
$arr_get = get_updatedvalues($form,$array);
Running this I get:
Array
(
[field] => Array
(
[field_one] => Array
(
[name] => field_one
[old_value] => old
[new_value] => new
)
[field_two] => Array
(
[name] => field_two
[old_value] => old
[new_value] => new
)
[field_four] => Array
(
[name] => field_four
[old_value] => old
[new_value] => new
)
)
)

Meaning of array in wordpress

So I am working with wordpress and using the following code I get the following. I know this must be a basic question but I want to know what it means:
[1012] => Array ( [0] => 1 )
[1013] => Array ( [0] => 0 )
[1014] => Array ( [0] => 0 )
[1018] => Array ( [0] => 0 )
PHP:
<?php
$all_meta_for_user = get_user_meta(get_current_user_id());
print_r( $all_meta_for_user );
?>
This data is user's metadata https://codex.wordpress.org/Function_Reference/get_user_meta
As you say, this is your metadata. Two things here: first of all, I'll store all that data together inside a single key and I'll remove the uneeded single-element array:
[my_plugin] => Array( [1012] => 1, [1013] => 0 ...)
That lowers the possibility of your data mixing with other's plugin data, having conflicts, etc. Also, as second array is probably not needed, it will make access to it a little simpler.
When you have that, it's only a matter of accessing the value like this:
if ($all_meta_for_user['my_plugin'][$id] == 1) show_the_post()
where $id is the post ID.
To use a single key, I'll do something like this (untested):
$posts_meta_for_user = get_user_meta(get_current_user_id(), 'my_plugin', true);
if (is_array($posts_meta_for_user)) {
$posts_meta_for_user[$new_id] = $new_value;
update_user_meta(get_current_user_id(), 'my_plugin', $posts_meta_for_user);
} else {
$posts_meta_for_user = array($new_id => $new_value);
add_user_meta(get_current_user_id(), 'my_plugin', $awesome_level);
}
Notice that we get only the meta value named 'my_plugin' and test it already had a value by checking that is an array. If it is, we update it, and if it's not, we create a new one. $new_id is the post ID you want to store and $new_value the value.

Create multidimensional array from standard array

Most likely I'm doing this wayyyyyy too complicated. But I'm in the need of converting multiple arrays to multidimensional array key's. So arrays like this:
Array //$original
(
[0] => 500034
[1] => 500035 //these values need to become
//consecutive keys, in order of array
)
Needs to become:
Array
(
[50034][50035] => array()
)
This needs to be done recursively, as it might also require that it becomes deeper:
Array
(
[50034][50036][50126] => array() //notice that the numbers
//aren't necessarily consecutive, though they are
//in the order of the original array
)
My current code:
$new_array = array();
foreach($original as $k => $v){ //$original from first code
if((gettype($v) === 'string' || gettype($v) === 'integer')
&& !array_key_exists($v, $original)){ //check so as to not have illigal offset types
$new_array =& $original[array_search($v, $original)];
echo 'In loop: <br />';
var_dump($new_array);
echo '<br />';
}
}
echo "After loop <br />";
var_dump($new_array);
echo "</pre><br />";
Gives me:
In loop:
int(500032)
In loop:
int(500033)
After loop
int(500033)
Using this code $new_array =& $original[array_search($v, $original)]; I expected After loop: $new_array[50034][50035] => array().
What am I doing wrong? Been at this for hours on end now :(
EDIT to answer "why" I'm trying to do this
I'm reconstructing facebook data out of a database. Below is my own personal data that isn't reconstructing properly, which is why I need the above question answered.
[500226] => Array
(
[own_id] =>
[entity] => Work
[name] => Office Products Depot
[500227] => Array
(
[own_id] => 500226
[entity] => Employer
[id] => 635872699779885
)
[id] => 646422765379085
)
[500227] => Array
(
[500228] => Array
(
[own_id] => 500227
[entity] => Position
[id] => 140103209354647
)
[name] => Junior Programmer
)
As you can see, the ID [500227] is a child of [500226], however, because I haven't got the path to the child array, a new array is created. The current parentage only works to the first level.
[own_id] is a key where the value indicates which other key should be its parent. Which is why the first array ([500226]) doesn't have a value for [own_id].
If you want to do something recursively, do it recursively. I hope that's what you meant to do.
public function pivotArray($array, $newArray)
{
$shifted = array_shift($array);
if( $shifted !== null )
{
return $this->pivotArray($array, array($shifted=>$newArray));
}
return $newArray;
}
$array = array(432, 432532, 564364);
$newArray = $this->pivotArray($array, array());
Edit: After the question's edit it doesn't seem to be very relevant. Well, maybe someone will find it useful anyway.

Combining and eliminating keys value pairs in array

A PHP question about arrays. Suppose we have two arrays:
[first] => Array
(
[0] => users
[1] => posts
[2] => comments
)
[second] => Array
(
[users] => the_users
[posts] => the_posts
[comments] => the_comments
[options] => the_options
)
How can I compare these two arrays? Meaning, how can we check whether or not the value in the first array is equal to the key in the second array (array_flip?) after combining them somehow (array_merge?). And whichever value/key pair matches, remove them from the array.
Basically, the end result would be the two arrays combined, duplicates removed, and the only index will be:
[third] => Array
(
[options] => the_options
)
try this:
$third = array_diff_key($second,array_flip($first));
There could be a built-in function for this, but if there isn't, try:
$third = array();
foreach(array_keys($second) as $item)
if(!in_array($item, $first))
$third[$item] = $second[$item];
Note that this assumes that $first will not have an item that doesn't have a corresponding key in $second. To account for this, you could have an additional loop (I don't know what you would set the value in $third to for these, maybe null:
foreach($first as $item)
if(!in_array($item, array_keys($second)))
$third[$item] = null;
This is pretty simple to do and this way is extremely efficient:
$third = $second;
foreach($first as $value)
{
if (isset($third[$value]))
{
unset($third[$value]);
}
}
this is the answer to ur question
$first= array
(
"0" => "users",
"1" => "posts",
"2" => "comments"
);
$firstf=array_flip($first);
$second = array
(
"users" => "the_users",
"posts" => "the_posts",
"comments" => "the_comments",
"options" => "the_options"
);
$third=array_diff_key($second,$firstf);
print_r($third);

checking to see if a vaule is in a particular key of an array

I'm new to working with arrays so I need some help. With getting just one vaule from an array. I have an original array that looks like this:
$array1= Array(
[0] => 1_31
[1] => 1_65
[2] => 29_885...)
What I'm trying to do is seach for and return just the value after the underscore. I've figured out how to get that data into a second array and return the vaules as a new array.
foreach($array1 as $key => $value){
$id = explode('_',$value);
}
which gives me:
Array ( [0] => 1 [1] => 31 )
Array ( [0] => 1 [1] => 65 )
Array ( [0] => 29 [1] => 885 )
I can also get a list of the id's or part after the underscore by using $id[1] I'm just not sure if this is the best way and if it is how to do a search. I've tried using in_array() but that searches the whole array and I couldn't make it just search one key of the array.
Any help would be great.
If the part after underscore is unique, make it a key for new array:
$newArray = array();
foreach($array1 as $key => $value){
list($v,$k) = explode('_',$value);
$newArray[$k] = $v;
}
So you can check for key existence with isset($newArray[$mykey]), which will be more efficient.
You can use preg_grep() to grep an array:
$array1= array("1_31", "1_65", "29_885");
$num = 65;
print_r(preg_grep("/^\d+_$num$/", $array1));
Outputs:
Array
(
[1] => 1_65
)
See http://ideone.com/3Fgr8
I would say you're doing it just about as well as anyone else would.
EDIT
Alternate method:
$array1 = array_map(create_function('$a','$_ = explode("_",$a); return $_[1];'),$array1);
echo in_array(3,$array1) ? "yes" : "no"; // 3 being the example
I would have to agree. If you wish to see is a value exists in an array however just use the 'array_key_exists' function, if it returns true use the value for whatever.

Categories