I need the Id if the 'Final' text match on this array. Like this for array one 288617 and for array two 288031.
Array
(
[0] => a:4:{i:0;s:11:"Demo Course";i:1;s:6:"288616";i:2;s:10:"Final Exam";i:3;s:6:"288617";}
)
Array
(
[0] => a:29:{i:0;s:16:"Sage 50 Accounts";i:1;s:6:"287967";i:2;s:6:"278823";i:3;s:6:"278824";i:4;s:6:"278825";i:5;s:6:"278826";i:6;s:6:"278856";i:7;s:6:"278857";i:8;s:6:"278858";i:9;s:6:"278859";i:10;s:6:"278860";i:11;s:6:"278861";i:12;s:6:"278862";i:13;s:6:"279608";i:14;s:6:"279609";i:15;s:6:"279610";i:16;s:6:"279611";i:17;s:6:"278821";i:18;s:6:"279612";i:19;s:6:"279613";i:20;s:6:"279681";i:21;s:6:"279677";i:22;s:6:"279678";i:23;s:6:"279679";i:24;s:6:"279680";i:25;s:9:"Mock Exam";i:26;s:6:"288030";i:27;s:10:"Final Exam";i:28;s:6:"288031";}
)
I have tried with this code, but can't work.
$search_text = 'Final';
array_filter($array, function($el) use ($search_text) {
return ( strpos($el['text'], $search_text) !== false );
});
First you have to unserialize that text. Then the simplest way is to loop and check for the text and then take the next element:
$array[0] = unserialize($array[0]);
$search_text = 'Final';
foreach($array[0] as $key => $value){
if(strpos($value, $search_text) !== false) {
$result = $array[0][$key+1];
break;
}
}
This assumes that the array is paired the way you have shown:
Array
(
[0] => Demo Course
[1] => 288616
[2] => Final Exam
[3] => 288617
)
With your second array it would only return the first ID 287967 if you search on Sage.
Try end function.
This function return the last element of your array
$array = ['sample1', 'sample2', ... ,'Final';
$search_text = 'Final';
if(end($aray) == $search_text){
// find
}else{
// not found
}
Related
I have 2 arrays -
$array1 =
Array
(
[0] => Array
(
[user_id] => 2
[like_status] => 1
)
[1] => Array
(
[user_id] => 3
[like_status] => 1
)
)
$array2 =
Array
(
[isLoggedIn] => 1
[userId] => 3
)
My requirement is I want to fetch the array where userId = 3. There can be multiple records in $array1 But I only want to fetch the array which have userID = 3, which is in $array2
I am able to get into the condition and match but not able to fetch.
if(array_search($array2['userId'], array_column($array1, 'user_id')) !== False) {
print_r($array1);
}
But it should only return the specific array.
One method is to create a flat array of the userid and use array_intersect to get the matching full arrays.
$userids = array_column($array1, "user_id");
$matching = array_intersect_key($array1, array_intersect($userids, [$array2['user_id']]));
Now $matching will be all the $array1 subarrays where userid is matching $array2['userId'].
array_search($array2['userId'], array_column($array1, 'user_id'))
Will return the index of a matching item or false if there is no matching item. You can use this info to grab the array from $array1.
I.e.
$index = array_search($array2['userId'], array_column($array1, 'user_id')) !== False);
if($index !== false){
print_r($array1[$index]);
}
Note that this assumes that there is only one matching user id in the array - if there are more only the first will be found.
You can do this using foreach also, if you want to like below
foreach ($array1 as $key => $value) {
if($value['user_id'] == $array2['userId'])
{
echo '<pre>'; print_r($value);echo '</pre>';
break;
}
}
Output :
Array (
[user_id] => 3
[like_status] => 1 )
you can achieve this using foreach loop
foreach( $array1 as $val ){
$val['user_id'] == $array2['userId'] ? $result[] = $val : '';
}
echo "<pre>"; print_r( $result );
I am using ajax to submit the form and ajax value post as:
newcoach=6&newcoach=11&newcoach=12&newcoach=13&newcoach=14
In PHP I am using parse_str to convert string to array,but it return only last value:
$newcoach = "newcoach=6&newcoach=11&newcoach=12&newcoach=13&newcoach=14";
$searcharray = array();
parse_str($newcoach, $searcharray);
print_r($searcharray);
Result array having only last value:
Array
(
[newcoach] => 14
)
Any help will be appreciated...
Since you set your argument newcoach multiple times, parse_str will only return the last one. If you want parse_str to parse your variable as an array you need to supply it in this format with a '[ ]' suffix:
$newcoach = "newcoach[]=6&newcoach[]=11&newcoach[]=12&newcoach[]=13&newcoach[]=14";
Example:
<?php
$newcoach = "newcoach[]=6&newcoach[]=11&newcoach[]h=12&newcoach[]=13&newcoach[]=14";
$searcharray = array();
parse_str($newcoach, $searcharray);
print_r($searcharray);
?>
Outputs:
Array ( [newcoach] => Array ( [0] => 6 [1] => 11 [2] => 12 [3] => 13 [4] => 14 ) )
Currently it is assigning the last value as all parameter have same name.
You can use [] after variable name , it will create newcoach array with all values within it.
$test = "newcoach[]=6&newcoach[]=11&newcoach[]=12&newcoach[]=13&newcoach[]=14";
echo '<pre>';
parse_str($test,$result);
print_r($result);
O/p:
Array
(
[newcoach] => Array
(
[0] => 6
[1] => 11
[2] => 12
[3] => 13
[4] => 14
)
)
Use this function
function proper_parse_str($str) {
# result array
$arr = array();
# split on outer delimiter
$pairs = explode('&', $str);
# loop through each pair
foreach ($pairs as $i) {
# split into name and value
list($name,$value) = explode('=', $i, 2);
# if name already exists
if( isset($arr[$name]) ) {
# stick multiple values into an array
if( is_array($arr[$name]) ) {
$arr[$name][] = $value;
}
else {
$arr[$name] = array($arr[$name], $value);
}
}
# otherwise, simply stick it in a scalar
else {
$arr[$name] = $value;
}
}
# return result array
return $arr;
}
$parsed_array = proper_parse_str($newcoach);
here is my array:
[0] => Array
(
[messages] => Array
(
[0] => Array
(
[message] => This is for sandwich
)
[1] => Array
(
[message] => This message is for burger
)
)
[price] => Array
(
[amount] => 5
[currency] => USD
)
[1] => Array
(
[messages] => Array
(
[0] => Array
(
[message] => This is a message for a delicious hotdog
)
)
[price] => Array
(
[amount] => 3
[currency] => USD
)
)
i want to search in ALL arrays and I want to search for the word "burger". I want to get the price and amount of "burger" which is 5. If I search for the word "hotdog", it will return the price amount 3. How can i do that? thanks
You can use a foreach loop and then use strpos or stripos.
foreach ($array as $row) {
foreach ($row['messages'] as $row2) {
if(strpos($row2['message'], 'burger') !== false) {
$stringFound = true;
} else {
$stringFound = false;
}
}
if($stringFound === true) {
$price = $row['price']['amount'];
} else {
$price = '0';
}
}
echo $price;
If $array be your array. I Think It may Work.
<?php
$check = 'hotdog';
foreach($array as $products){
foreach($products['messages'] as $messages){
if (strpos($messages['message'], $check) !== false) {
echo $check.' Found. Price'. $products['price']['amount'] .'</br>' ;
}
}
}
?>
Here we are using array_column, implode and preg_match.
1. array_column for retrieving specific column of an array
2. implode joins a array with a glue to make it string.
3. preg_match here for matching specific word in the given string.
Try this code snippet here
$toSearch="hotdog";
foreach($array as $key => $value)
{
if(preg_match("/\b$toSearch\b/",implode(",",array_column($value["messages"],"message"))))
{
echo $value["price"]["amount"];
}
}
Because you are searching for the first qualifying price only, it is best practice to use a conditional break to short circuit the loops. There is no reason to do more cycles if you have found a qualifying entry.
Instantiate the $amount variable with a null value before the loop to properly distinguish between a successful search and an unsuccessful one.
str_contain() is the modern function to case-sensitively search for a substring (PHP7.4 and higher). If you need case-insensitivity, you will need to use stripos($message['message'], $needle) !== false. If you need to match whole words, you will need to call preg_match("/\b$needle\b/i", $message['message']). If using regex and the $needle is coming from user input, you will need to apply escaping beforehand with $needle = preg_quote($needle, '/');.
Code: (Demo)
$needle = 'burger';
$amount = null;
foreach ($haystack as ['messages' => $messages, 'price' => $price]) {
foreach ($messages as $message) {
if (str_contains($message['message'], $needle)) {
$amount = $price['amount'];
break;
}
}
}
var_export($amount);
// 5
Well this has been a headache.
I have two arrays;
$array_1 = Array
(
[0] => Array
(
[id] => 1
[name] => 'john'
[age] => 30
)
[1] => Array
(
[id] => 2
[name] => 'Amma'
[age] => 28
)
[2] => Array
(
[id] => 3
[name] => 'Francis'
[age] => 29
)
)
And another array
array_2 = = Array
(
[0] => Array
(
[id] => 2
[name] => 'Amma'
)
)
How can I tell that the id and name of $array_2 are the same as the id and name of $array_1[1] and return $array_1[1]['age']?
Thanks
foreach($array_1 as $id=>$arr)
{
if($arr["id"]==$array_2[0]["id"] AND $arr["name"]==$array_2[0]["name"])
{
//Do your stuff here
}
}
Well you can do it in a straightforward loop. I am going to write a function that takes the FIRST element in $array_2 that matches something in $array_1 and returns the 'age':
function getField($array_1, $array_2, $field)
{
foreach ($array_2 as $a2) {
foreach ($array_1 as $a1) {
$match = true;
foreach ($a2 as $k => $v) {
if (!isset($a1[$k]) || $a1[$k] != $a2[$k]) {
$match = false;
break;
}
}
if ($match) {
return $a1[$field];
}
}
}
return null;
}
Use array_diff().
In my opinion, using array_diff() is a more generic solution than simply comparing the specific keys.
Array_diff() returns a new array that represents all entries that exists in the first array and DO NOT exist in the second array.
Since your first array contains 3 keys and the seconds array contains 2 keys, when there's 2 matches, array_diff() will return an array containing the extra key (age).
foreach ($array_1 as $arr) {
if (count(array_diff($arr, $array_2[1])) === 1) {//meaning 2 out of 3 were a match
echo $arr['age'];//prints the age
}
}
Hope this helps!
I assume you want to find the age of somebody that has a known id and name.
This will work :
foreach ($array_1 as $val){
if($val['id']==$array_2[0]['id'] && $val['name']==$array_1[0]['name']){
$age = $val['age'];
}
}
echo $age;
Try looking into this.
http://www.w3schools.com/php/func_array_diff.asp
And
comparing two arrays in php
-Best
I have this array:
$array = array(
[0] => "obm=SOME_TEXT",
[1] => "sbm=SOME_TEXT",
[2] => "obm=SOME_TEXT"
);
How can I remove array's element(s) containing value obm or sbm (which is always at the top of the string in the array) and update indexes?
Example 1:
print_r(arrRemove("smb", $array));
Output:
$array = array(
[0] => "obm=SOME_TEXT",
[1] => "obm=SOME_TEXT"
);
Example 2:
print_r(arrRemove("omb", $array));
Output:
$array = array(
[0] => "sbm=SOME_TEXT"
);
You can simply loop through the array using a foreach and then use strpos() to check if the array contains the given input string, and array_values() to update the indexes:
function arrRemove($str, $input) {
foreach ($input as $key => $value) {
// get the word before '='
list($word, $text) = explode('=', $value);
// check if the word contains your searchterm
if (strpos($word, $str) !== FALSE) {
unset($input[$key]);
}
}
return array_values($input);
}
Usage:
print_r(arrRemove('obm', $array));
print_r(arrRemove('sbm', $array));
Output:
Array
(
[0] => sbm=SOME_TEXT
)
Array
(
[0] => obm=SOME_TEXT
[1] => obm=SOME_TEXT
)
Demo!
Maybe something like this?
$newarray = array_values(array_filter($oldarray, function($value){
return strpos($value, 'obm') !== 0;
}
));
This is handled by PHP
php.net/manual/en/function.array-pop.php
array_pop() pops and returns the last value of the array , shortening the array by one element.