I have this string that I'm Getting from a Mysql Result:
Result1:
1/test3&2/test4&
Then, I have some ID from another mysql Result like this:
Result2:
$id = $row['id'];
Then I'm using an Explode in order to separate Result1:. Like I'm Getting this:
$nota3 = explode("&", $nota);
1/test3&
2/test4&
Now, I'm doing I'm using a foreach and then using another explode to separate the string by "/" delimiter.
foreach ($nota3 as $key) {
$nota4 = explode("/", $key);
}
The Result of this its something like this (for the firsts foreach iteration):
array(2) {
[0]=>
string(1) "1"
[1]=>
string(5) "test3"
}
Ok, So I cannot Compare nota4[0] with $id from Result2:
Things that I've Tried:
Using if and verify every type, converts nota4[0] a $id to string
Try to use in_Array
Try to use strcmp($var1, $var2)
I'm Missing something but I really dont know what.
Also, when I tried I cant put nota4[0] into a html String like
$nota5= nota4[0];
echo "<p id='mic' class='text-dark bg-warning'>".$nota5."</p>";
Maybe its something silly but I tried everything without success.
You can make sure both are strings and trim and use a strict operator - even if it seems they are already that
$result1 = "1/test3&2/test4&";
$result2 = "1";
$id = trim((string) $result2);
foreach ($nota3 as $key) {
$nota4 = explode("/", $key);
if (trim((string) $nota4[0]) === $id) {
//...
}
}
Here's another way to go about it. This will set up $result1 (or you can rename it) to become an associative array of key/value pairs, allowing you to loop through and compare a value like $result2 with a key id in the $result1 array. Example link included.
<?php
$result1 = "1/test3&2/test4&";
$result2 = "1";
$result1 = array_map(function ($a) {
$tmp = explode("/", $a);
return array('id' => $tmp[0],'name' => $tmp[1]);
}, array_filter(explode("&", $result1)));
print_r($result1);
now to get $result2
foreach ($result1 as $item) {
if ($item['id'] == $result2) {
// $value
}
}
Output of result1
[0] => Array
(
[id] => 1
[name] => test3
)
[1] => Array
(
[id] => 2
[name] => test4
)
https://www.tehplayground.com/1436vTBhUOYx9MNX
Related
I have strings in following format:
$strings[1] = cat:others;id:4,9,13
$strings[2] = id:4,9,13;cat:electric-products
$strings[3] = id:4,9,13;cat:foods;
$strings[4] = cat:drinks,foods;
where cat means category and id is identity number of a product.
I want to split these strings and convert into arrays $cats = array('others'); and $ids = array('4','9','13');
I know that it can be done by foreach and explode function through multiple steps. I think I am somewhere near, but the following code does not work.
Also, I wonder if it can be done by preg_match or preg_split in fewer steps. Or any other simpler method.
foreach ($strings as $key=>$string) {
$temps = explode(';', $string);
foreach($temps as $temp) {
$tempnest = explode(':', $temp);
$array[$tempnest[0]] .= explode(',', $tempnest[1]);
}
}
My desired result should be:
$cats = ['others', 'electric-products', 'foods', 'drinks';
and
$ids = ['4','9','13'];
One option could be doing a string compare for the first item after explode for cat and id to set the values to the right array.
$strings = ["cat:others;id:4,9,13", "id:4,9,13;cat:electric-products", "id:4,9,13;cat:foods", "cat:drinks,foods"];
foreach ($strings as $key=>$string) {
$temps = explode(';', $string);
$cats = [];
$ids = [];
foreach ($temps as $temp) {
$tempnest = explode(':', $temp);
if ($tempnest[0] === "cat") {
$cats = explode(',', $tempnest[1]);
}
if ($tempnest[0] === "id") {
$ids = explode(',', $tempnest[1]);
}
}
print_r($cats);
print_r($ids);
}
Php demo
Output for the first item would for example look like
Array
(
[0] => others
)
Array
(
[0] => 4
[1] => 9
[2] => 13
)
If you want to aggregate all the values in 2 arrays, you can array_merge the results, and at the end get the unique values using array_unique.
$strings = ["cat:others;id:4,9,13", "id:4,9,13;cat:electric-products", "id:4,9,13;cat:foods", "cat:drinks,foods"];
$cats = [];
$ids = [];
foreach ($strings as $key=>$string) {
$temps = explode(';', $string);
foreach ($temps as $temp) {
$tempnest = explode(':', $temp);
if ($tempnest[0] === "cat") {
$cats = array_merge(explode(',', $tempnest[1]), $cats);
}
if ($tempnest[0] === "id") {
$ids = array_merge(explode(',', $tempnest[1]), $ids);
}
}
}
print_r(array_unique($cats));
print_r(array_unique($ids));
Output
Array
(
[0] => drinks
[1] => foods
[3] => electric-products
[4] => others
)
Array
(
[0] => 4
[1] => 9
[2] => 13
)
Php demo
I don't generally recommend using variable variables, but you are looking for a sleek snippet which uses regex to avoid multiple explode() calls.
Here is a script that will use no explode() calls and no nested foreach() loops.
You can see how the \G ("continue" metacharacter) allows continuous matches relative the "bucket" label (id or cat) by calling var_export($matches);.
If this were my own code, I'd probably not create separate variables, but a single array containing id and cat --- this would alleviate the need for variable variables.
By using the encountered value as the key for the element to be added to the bucket, you are assured to have no duplicate values in any bucket -- just call array_values() if you want to re-index the bucket elements.
Code: (Demo) (Regex101)
$count = preg_match_all(
'/(?:^|;)(id|cat):|\G(?!^),?([^,;]+)/',
implode(';', $strings),
$matches,
PREG_UNMATCHED_AS_NULL
);
$cat = [];
$id = [];
for ($i = 0; $i < $count; ++$i) {
if ($matches[1][$i] !== null) {
$arrayName = $matches[1][$i];
} else {
${$arrayName}[$matches[2][$i]] = $matches[2][$i];
}
}
var_export(array_values($id));
echo "\n---\n";
var_export(array_values($cat));
All that said, I probably wouldn't rely on regex because it isn't very readable to the novice regex developer. The required logic is much simpler and easier to maintain with nested loops and explosions. Here is my adjustment of your code.
Code: (Demo)
$result = ['id' => [], 'cat' => []];
foreach ($strings as $string) {
foreach (explode(';', $string) as $segment) {
[$key, $values] = explode(':', $segment, 2);
array_push($result[$key], ...explode(',', $values));
}
}
var_export(array_unique($result['id']));
echo "\n---\n";
var_export(array_unique($result['cat']));
P.s. your posted coding attempt was using a combined operator .= (assignment & concatenation) instead of the more appropriate combined operator += (assignment & array union).
I have known the cause of the problem, not in the code.
Content of the field at the base value of each line separately
So used str_replace to delete the line
$query = $db->query_first("SELECT * FROM table ");
$array1 = explode(",",$query[filed1]);
$array1 = str_replace("\n","",$array1);
$array2 = explode(",",$query[filed2]);
$array2 = str_replace("\n","",$array2);
foreach($array1 as $value)
{
if (in_array($value,$array2))
{
//true
}else{
//false
}
}
I have a problem when I check if Each value in $array2 is present in $array1 or not
Table data:
filed1 | filed2
ahmed,jon,maya,omar | omar,maya
My code:
$query = $db->query_first("SELECT * FROM table ");
$array1 = explode(",",$query[filed1]);
$array2 = explode(",",$query[filed2]);
$length = count($array1);
for ($i = 0; $i < $length; $i++)
{
if (in_array($array1[$i] , $array2))
{
//true
}else{
//false
}
}
or this:
$query = $db->query_first("SELECT * FROM table ");
$array1 = explode(",",$query[filed1]);
$array2 = explode(",",$query[filed2]);
foreach($array1 as $value)
{
if (in_array($value,$array2))
{
//true
}else{
//false
}
}
My problem is my code doesn't work good, I am sure that my query gives the results and arrays too.
Output of array1:
Array ( [0] => maya [1] => omar [2] => ahmed [3] => join)
Output of array2:
Array ( [0] => omar [1] => maya )
So, where is the error in my code?!
Note :
I don't want check all value from array2 are in array1, I want check if Each value in $array2 is present in $array1 or not - focus on this word Each value not all value
Like:
if (in_array('omar',$array1))
{
echo 'found';
}else{
echo 'not found'; }
if (in_array('maya',$array1))
{
echo 'found';
}else{
echo 'not found';
}
if (in_array('jon',$array1))
{
echo 'found';
}else{
echo 'not found';
}
etc ...
But I do not want it this way, I want it inside a loop.
Yes you can use a loop in this case if you really want to, a simple foreach should suffice:
$array1 = array_map('trim', $array1); // on explode make sure remove trailing/leading spaces
$array2 = array_map('trim', $array2);
foreach($array1 as $name) { // so each value of array1
if(in_array($name, $array2)) { // is compared inside the contents of array2
// if found
echo "$name is found in " . '$array2';
} else {
echo "$name is NOT found in " . '$array2';
}
}
I think you should be iterating over array2 so all values of array2 are checked, not the other way around, because you said: "
check if Each value in $array2...
$query = $db->query_first("SELECT * FROM table ");
$array1 = explode(",",$query['filed1']);
$array2 = explode(",",$query['filed2']);
foreach($array2 as $value)
{
if (in_array($value,$array1))
{
//true
}else{
//false
}
}
I have known the cause of the problem, not in the code ...
Content of the field at the base value of each line separately
So used str_replace to delete the line
$query = $db->query_first("SELECT * FROM table ");
$array1 = explode(",",$query[filed1]);
$array1 = str_replace("\n","",$array1);
$array2 = explode(",",$query[filed2]);
$array2 = str_replace("\n","",$array2);
foreach($array1 as $value)
{
if (in_array($value,$array2))
{
//true
}else{
//false
}
}
array_diff() is a single function approach to getting an array of items not present in further arrays
$array1 = array('ahmed','jon','maya','omar');
$array2 = array('omar','maya');
$result = array_diff($array1,$array2); // Array ( [0] => ahmed [1] => jon )
you may need to switch parameter order to achieve your desired outcome.
you can also use array_intersect() to perform the reverse
#Ghost's solution produced the correct output, but as you state, you know the problem isn't your code. Apparently the problem is that the format of the data you are querying isn't quite matching. So, here is how you can approach debugging this problem:
var_dump() the data
The likely suspect is that some of the data have padding. (It's odd that #Ghost's suggestion of trimming the results didn't work.)
$array1 = explode(",",$query['filed1']);
$array2 = explode(",",$query['filed2']);
var_dump($array1);
echo "\n";
var_dump($array2);
echo "\n";
Inspect comparisons in the iteration
The above should reveal the problem. If not, you could take it a step deeper and see which exact comparison is failing in the in_array. If you don't have xdebug available, just loop within the loop:
foreach ($array1 as $value) {
if (in_array($value, $array2)) {
echo "\n[$value found in \$array2]\n";
} else {
echo "\n[$value NOT found in \$array2]\n";
}
foreach ($array2 as $value2) {
if ($value !== $value2) {
echo "\$array1's '$value' !== \$array2's '$value2'\n";
} else {
echo "\$array1's '$value' === \$array2's '$value2'\n";
}
}
}
The output will show you exactly what is wrong.
Note: You should include filed1 and filed2 in quotes since you are using them as string keys. When PHP parses your code, it will emit a notice (error) and fall back on interpreting it as a string.
I have created this
while ($data = mysqli_fetch_array($course_result, MYSQLI_ASSOC)) {
print_r($data['course']);
}
Which prints this:
Array (
[user_id] => 57
[course] => 6
)
Array (
[user_id] => 57
[course] => 5
)
How can I create two variables that are equal to the values of the 'course' fields.
So ideally, variable x ends up equalling to 6 and variable y equals 5 (essentially what I'm asking is how to extract the value from the mysql arrays and putting it into a variable)?
There is no something as you called "mysql_arrays". They are normal arrays.
You can do for example:
$array = array();
while ($data = mysqli_fetch_array($course_result, MYSQLI_ASSOC)) {
$array[] = $data; // probably this way and not $array[] = $data['course'];
}
$x = $array[0]['course'];
$y = $array[1]['course'];
I would suggest you using an array instead of a variable to store the values.
$arr= array();
while ($data = mysqli_fetch_array($course_result, MYSQLI_ASSOC)) {
$arr[] = $data['course'];
}
Speculating a bit as don't have the full picture but I guess you're after something like this.
Get an array of the courses from your data
$data = array_map(function($value) {
return $value['course'];
}, $data);
If there are only ever two results, assign each one to a variable :
list($x, $y) = $data;
If there are more than two results, you have an array of courses in $data from your query results.
I'm building application that tells user which are old and which are new bank notes when I increase sum with X. Everything is fine, but I'm wondering how I can now get list of added and removed items of array?
$old = array(1,5,10);
$new = array(1,5,1);
$added = array_diff($new,$old);
$removed = array_diff($old,$new);
And this is what code above returns:
$added is array(). Incorrect, it should be array([2] => 1).
$removed is array([2] => 10). Correct.
What am I doing wrong, and how can I fix it?
$added = array_diff($new,$old);
In the above statement, array_diff() compares $new with $old and returns the values in $new that are not present in $old. There is no such value, and hence it returns an empty array.
In short, array_diff() doesn't work with duplicate values. You will have to write a custom function to achieve this. Here's an example:
function array_diff_once($array1, $array2) {
foreach($array2 as $val) {
if (false !== ($pos = array_search($val, $array1))) {
unset($array1[$pos]);
}
}
return $array1;
}
You can simply use it the same way you did before:
$added = array_diff_once($new,$old);
$removed = array_diff_once($old,$new);
print_r() of these arrays would correctly output:
Array
(
[2] => 1
)
Array
(
[2] => 10
)
Working demo
If you want to check the keys in addition to the values of an array, you should use array_diff_assoc() instead of array_diff():
<?php
$old = array(1,5,10);
$new = array(1,5,1);
$added = array_diff_assoc($new,$old);
$removed = array_diff_assoc($old,$new);
echo "<pre>\n"; \\ prints array(1) { [2]=> int(1) }
var_dump($added);
var_dump($removed);
echo "</pre>\n";
?>
since im newbie i have a question
well i have $nUserID where store user's id's and is like
int(1)
int(2)
int(1)
and in $nAuctionID i have items id and they are like
int(150022)
int(150022)
int(150031)
i need put it in 1 array and make it like
array (
[1] => 150022
[2] => 120022,150031
)
which user which item id watch
how to do that ?
i though should use foreach , but i cant imagine how will looks
start with
$u[] = $nUserID;
$i[] = $nAuctionID;`
Grouping them by user ID, the following should result in what you're looking for.
$usersWatching = array();
// The following results in:
// array(1 => array(150022, 150023), 2 => array(150022))
// Which should be way more useful.
foreach ($nUserID as $i => $userID)
{
if (!isset($usersWatching[$userID]))
$usersWatching[$userID] = array();
$usersWatching[$userID][] = $nAuctionID[$i];
}
// To get the comma-separated version, do this:
$usersWatching = array_map(function ($value) {
return implode(',', $value);
}, $usersWatching);
this will work :
$arr = array();
foreach( $nUserID as $key=>$value)
{
$arr[$value] = $nAuctionID[$key] ;
}
print_r($arr);
Most confusingly worded question EVA!
$outputArray = array();
for ($i=0; $i< count($nUserID); $i++) {
$outputArray[$nUserID[$i]] = $nAuctionID[$i];
}
echo "<pre>";
print_r($outputArray);
That is what I got from your question..