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);
Related
Lets say I have the following array:
$arr = array("exercise__2" => "Then a set", "sets__2" => 3, "exercise__4" => "And finally a set", "sets__4" => 3);
What I'm now trying to do is to convert this array into a multidimensional array every time the number changes in the key.
I know we have to use explode("__", $key), but I can't work out how to convert it to a multidimensional array so it would appear something like the following:
Array
(
Array
(
[exercise__2] => Then a set
[sets__2] => 3
)
Array
(
[exercise__4] => And finally a set
[sets__4] => 3
)
)
I suspect it's not too difficult but I'm frying my brain trying to work it out.
Simple for loop should do it:
$arr = array("exercise__2" => "Then a set", "sets__2" => 3, "exercise__4" => "And finally a set", "sets__4" => 3);
foreach($arr as $k =>$v) {
$res[explode("__", $k)[1]][$k] = $v;
}
You can use array_values if you don't want the extra key in the upper array.
Live example: 3v4l
Array_chunk seems to be enough.
Array_chunk splits an array with n number of items.
The third argument is to preserve keys.
$arr = array("exercise__2" => "Then a set", "sets__2" => 3, "exercise__4" => "And finally a set", "sets__4" => 3);
$result = array_chunk($arr, 2, true);
print_r($result);
Output:
Array
(
[0] => Array
(
[exercise__2] => Then a set
[sets__2] => 3
)
[1] => Array
(
[exercise__4] => And finally a set
[sets__4] => 3
)
)
https://3v4l.org/s57ua
When I do a print_r on my $_POST, I have an array that may look like this:
Array
(
[action] => remove
[data] => Array
(
[row_1] => Array
(
[DT_RowId] => row_1
[name] => Unit 1
[item_price] => 150.00
[active] => Y
[taxable] => Y
[company_id] => 1
)
)
)
The row_1 value can be anything formatted like row_?
I want that number as a string, whatever the number is. That key and the DT_RowID value will always be the same if that helps.
Right now I am doing this, but it seems like a bad way of doing it:
//the POST is a multidimensinal array... the key inside the 'data' array has the id in it, like this: row_2. I'm getting the key value here and then removing the letters to get only the id nummber.
foreach ($_POST['data'] AS $key => $value) {
$id_from_row_value = $key;
}
//get only number from key = still returning an array
preg_match_all('!\d+!', $id_from_row_value, $just_id);
//found I had to use [0][0] since it's still a multidimensional array to get the id value
$id = $just_id[0][0];
It works, but I'm guessing there's a faster way of getting that number from the $_POST array.
<?php
$array = [
'data' => [
'row_1' => [],
'row_2' => [],
]
];
$nums = [];
foreach ($array['data'] as $key => $val) {
$nums[] = preg_replace('#[^\d]#', '', $key);
}
var_export($nums);
Outputs:
array (
0 => '1',
1 => '2',
)
Please remember that regular expressions, used in preg_match are not the fastest solution. What I would do is split the string by _ and take the second part. Like that:
$rowId = explode("_", "row_2")[1];
And put that into your loop to process all elements.
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']
);
}
}
}
Total PHP Noob and I couldn't find an answer to this specific problem. Hope someone can help!
$myvar is an array that looks like this:
Array (
[aid] => Array (
[0] => 2
[1] => 1
)
[oid] => Array(
[0] => 2
[1] => 1
)
)
And I need to set a new variable (called $attributes) to something that looks like this:
$attributes = array(
$myvar['aid'][0] => $myvar['oid'][0],
$myvar['aid'][1] => $myvar['oid'][1],
etc...
);
And, of course, $myvar may contain many more items...
How do I iterate through $myvar and build the $attributes variable?
use array_combine()
This will give expected result.
http://php.net/manual/en/function.array-combine.php
Usage:
$attributes = array_combine($myArray['aid'], $myArray['oid']);
Will yield the results as requested.
Somthing like this if I understood the question correct
$attributes = array();
foreach ($myvar['aid'] as $k => $v) {
$attributes[$v] = $myvar['oid'][$k];
}
Your requirements are not clear. what you mean by "And, of course, $myvar may contain many more items..." there is two possibilties
1st. more then two array in main array. like 'aid', 'oid' and 'xid', 'yid'
2nd. or two main array with many items in sub arrays like "[0] => 2 [1] => 1 [2] => 3"
I think your are talking about 2nd option if so then use following code
$aAid = $myvar['aid'];
$aOid = $myvar['oid'];
foreach ($aAid as $key => $value) {
$attributes['aid'][$key] = $value;
$attributes['oid'][$key] = $myvar['oid'][$key];
}
You can itterate though an array with foreach and get the key and values you want like so
$attributes = array()
foreach($myvar as $key => $val) {
$attributes[$key][0] = $val;
}
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.