I tried to use the function array_search but can't get it work..
I got a php session with an array.
array(2) {
[0]=>
array(6) {
["ProductId"]=>string(2) "34"
["ProductName"]=>string(9) "Best ever"
["ProductPrice"]=>string(6) "453.00"
["ProductColor"]=>string(4) "Blue"
["ProductSize"]=>string(1) "S"
["Image"]=>string(36) "d12f95895c9130da8e52a7ff5b9216c9.png"
}
[1]=>
array(6) {
["ProductId"]=>string(2) "33"
["ProductName"]=>string(5) "Vespa"
["ProductPrice"]=>string(7) "1789.00"
["ProductColor"]=>string(4) "Blue"
["ProductSize"]=>string(1) "S"
["Image"]=>string(36) "678e25ea94a7fa94bc6fa427ff29bc6c.png"
}
now I do an array_search()
session_start();
include '_sqlclean.php';
(isset($_POST['product_id'])) ? $p_id = clean_string_save($_POST['product_id']) : $p_id = 0;
$array = $_SESSION['wishList'];
$key = array_search($p_id, $array);
if I do a
var_dump($_SESSION['wishList']);
I got what I showed you above.
But I always got the message "Key not found"
Why ?? What's my mistake ?
I tried already to do
$p_id = "34" // for try
$p_id = intval(34); // for try also
$key = array_search("34", $_SESSION['wishList']); // to see if it works
but nothing worked.. :(
Thanks in advance
array_search will not work for multidimensional arrays. Rather this might work -
$key = array_search($p_id, array_column($array, 'ProductId'));
This will extract all the ProductId from that array then do the search.
Try with alternative for array_search().For example:
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['uid'] === $id) {
return $key;
}
}
return null;
}
OR
$key = array_search($p_id, array_column($array, 'ProductId'));
Aparently you are mistyping the variable (key) name
in the array it is
ProductId
and in your code it is
Product_Id
It happen cause you search into outer array, which contains only [0] and [1] keys.
Try to use
$key = array_search("34", $_SESSION['wishList'][1]);
You can try an alternative way like
<?php
$p_id = "34" // for try
$p_id = intval(34); // for try also
if(in_array($p_id, array_values($_SESSION['wishList']))) {
// Product Id found in your wishList
}
?>
It will works only for single dimension array. For multidimensional use foreach loop.
Related
So I have two arrays:
$gated_categories
array(2) { [0]=> int(3511) [1]=> int(3510) }
and
$category_id
array(3) { [0]=> int(3518) [1]=> int(3511) [2]=> int(3502) }
As you can see above, both arrays contain 3511
So if $gated_categories contains a value which is is $category_id
I want this to return true, else false
I have tried with this:
$is_gated = !array_diff($gated_categories, $category_id);
But this is returning false, any ideas?
array_diff() does the opposite of what you want. It returns an array with the values of the first array that are not present in the other array(s).
You need array_intersect().
if (count(array_intersect($arr1, $arr2))) {
//at least one common value in both arrays
}
You can do the following, loop over the array you want to check it's values and use in_array function.
Something like this:
<?php
function checkCategory(): bool {
$gated_categories = [3510, 3511];
$category_id = [3502, 3511, 3518];
foreach ($gated_categories as $cat) {
if (in_array($cat, $category_id)) {
return true;
}
}
return false;
}
var_dump(checkCategory());
You can solve this problem with use from array_diff two times
<?php
$gated_categories = [3511, 3510];
$category_id = [3518, 3511, 3502];
print_r(findGatedCategoriesContainCategoryId($gated_categories, $category_id));
function findGatedCategoriesContainCategoryId($gated_categories, $category_id) {
$arrayDiff = array_diff($gated_categories, $category_id);
return array_values(array_diff($gated_categories ,$arrayDiff));
}
?>
output
Array
(
[0] => 3511
)
Or just use array_intersect like this
<?php
$gated_categories = [3511, 3510];
$category_id = [3518, 3511, 3502];
$result = array_intersect($gated_categories, $category_id);
print_r($result);
?>
output
Array
(
[0] => 3511
)
I have an array of array like this
$data=array(
array("9900","1","7"),
array("9901","1","7"),
array("9902","1","7"),
array("9903","1","4"),
array("9904","3","8"),
array("9908","1","5")
);
I have value 9908. When I search 9908 then the value array("9908","1","5") should be printed. I have used array_search() but I have not got any success
How I can print the array after finding the value
Try this:
var_dump($data[array_search("9908", array_column($data, 0))]);
To expand it,
array_column returns the values from a single column of the input, identified by the column_key. Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array.
array_search Searches the array for a given value and returns the first corresponding key if successful.
Edit:
To add some control over it:
$index = array_search("9908", array_column($data, 0));
if($index !== false){
// do your stuff with $data[$index];
var_dump($data[$index]);
}
Dumps:
array(3) {
[0]=>
string(4) "9908"
[1]=>
string(1) "1"
[2]=>
string(1) "5"
}
Perhaps this can help:
<?php
function search_first_row($needle, $haystack){
$data = $haystack;
$desired_value = $needle;
foreach($data as $row){
if($row[0] == $desired_value){
return $row;
}
}
}
try this :
$data=array(
array("9900","1","7"),
array("9901","1","7"),
array("9902","1","7"),
array("9903","1","4"),
array("9904","3","8"),
array("9908","1","5")
);
foreach ($data as $key => $value) {
if( in_array("9908",$value)){
$findindex = $key;
}
}
var_dump($data[$findindex]);
$data=array(
array("9900","1","7"),
array("9901","1","7"),
array("9902","1","7"),
array("9903","1","4"),
array("9904","3","8"),
array("9908","1","5")
);
$searchValue = '9908';
for($i=0; $i<count($data); $i++){
$innerArray = $data[$i];
for($j=0; $j<count($innerArray); $j++){
if($innerArray[$j] == $searchValue){
print_r($innerArray);
}
}
}
My request data represents an array of new and existing items. I'm trying to through this array to update and create items.
This is how I retrieve the array:
$userInput = $request->all();
foreach( $userInput['items'] as $key=>&$item){
Later in the code I update an existing item:
$updateItem = Item::find($item['id']);
$updateItem->number = $item['number'];
$updateItem->save();
But $item['number'] seems to contain old input from previous updates and not the value I entered last time.
How can I loop through request data in Laravel ?
This is the whole code as I run it (want to get rid of confusion):
$userInput = $request->all();
// checking $userInput here
// I can see the new value in the array
foreach( $userInput['items'] as $key=>$item){
if($item['delete'] == 1) {
Item::where('order_id',$order->id)
->where('id',$item['id'])
->delete();
} else {
if(empty($item['id'])) {
} else {
$updateItem = Item::find($item['id']);
$updateItem->number = $item['id'];
$updateItem->save();
}
}
}
This is an input from html (just to show I checked the form also, the data comes just fine):
<input id="basicItemNumber-31" class="form-control" name="items[31][number]" placeholder="Unique number" value="31" type="text">
It's likely that somewhere inside your for you've inadvertently changed the value of your underling $item as you pass it by reference (using the & before the variable name.)
It's considered bad practice by some or most people as it can lead to "unexpected" behaviour, For example. take the sample code below that loops through an array of $items twice once by reference and once by value.
<?php
$items = ['one','two','three'];
foreach ($items as &$item) {
//do nothing.
}
foreach ($items as $item) {
//do nothing again.
}
var_dump($items);
//outputs
array(3) {
[0]=>
string(3) "one"
[1]=>
string(3) "two"
[2]=>
&string(3) "two"
}
Try something like this as it will keep your scope local:
$request['items']->each(function($item, $key) use ($order) {
if ($item->delete) {
Item::where('order_id',$order->id)
->where('id',$item['id'])
->delete();
} else {
if (!empty($item['id'])) {
$updateItem = Item::find($item['id']);
$updateItem->number = $item['id'];
$updateItem->save();
}
}
});
I am trying to locale the correct sub-array in order to change the count, if a specific value is present more than once.
I have the following code:
$trending = [];
foreach($hashtags as $hashtag) {
if(in_array($hashtag->hashtag, $hashtags))
{
array_search()
}
else {
array_push($trending, [
'hashtag' => $hashtag->hashtag,
'counts' => '1'
]);
}
}
This gives me the following example outout:
array(3) {
[0]=> array(2)
{
["hashtag"]=> "foobar"
["counts"]=> "1"
}
[1]=> array(2)
{
["hashtag"]=> "hashtags"
["counts"]=> "1"
}
[2]=> array(2)
{
["hashtag"]=> "imageattached"
["counts"]=> "1"
}
}
So in the foreach loop and the if statement, i want to check for dublicates of hashtags, e.g. if the hashtag foobar exists more than one time, I don't want to create another dublicate in the array, but I want to change the count to 2
How do I find the correct "sub"-array, and change the count of this to 2, if a hashtag is present within $hashtags more than once??
The idea is, that I at the end can sort these arrays, and get the hashtag that is most common, by looking at the count.
If you change the structure of your output, you could do something like this:
$trending = [];
foreach($hashtags as $tag) {
if (isset($trending[$tag])) $trending[$tag]++;
else $trending[$tag] = 1;
}
Which would result in $trending having the structure
array(2) {
["foobar"] => 1,
["hashtags"] => 2
}
Which could then be looped through with
foreach($trending as $tag => $count) {
echo $tag . ' appears ' . $count . ' times.' . PHP_EOL;
}
The PHP method array_count_values might be of some help.
http://php.net/manual/en/function.array-count-values.php
Have you considered using a keyed array?
$trending = array();
foreach($hashtags as $hashtag) {
if(!isset($trending[$hashtag])){
$trending[$hashtag] = 1;
}else{
$trending[$hashtag] += 1;
}
}
By using a keyed array, there is no duplication and you can easily check how frequently a hashtag is used by just accessing $trending[$hashtag]. Additionally, you can get the list of all hashtags in the trending array using $allHashtags = array_keys($trending);.
Of course, if your project specifications do not allow for this, then by all means, use a different approach, but that would be the approach I would take.
It can be more linear of you can change your array structure but for the current this should work.
$trending = [];
$checker = true;
foreach($hashtags as $hashtag) {
foreach ($trending as $key =>$value) {
if($value["hashtag"] == $hashtag->hashtag){
$trending[$key]["counts"]++;
$checker = false;
}
}
if($checker) {
array_push($trending, [
'hashtag' => $hashtag->hashtag,
'counts' => '1'
]);
}
$checker = true;
}
hopefully a easy one for you,
my sql query is returning a mulit-dimensional array, I need to access only one key the is nested on the second level but cant figure out how.
here is my function.
public function get_visitor_id($id)
{
$this->db->where('mobile',$id);
$this->db->or_where('email',$id);
$this->db->select('uid');
$result = $this->db->get('visitors');
if ($result)
{
foreach ($result->result() as $key=>$value){
$array[$key] = $value;
}
var_dump($array);
return $array;
}
}
The array returned is
{ [0]=> object(stdClass)#20 (1) { ["uid"]=> string(2) "24" } }
I only need the value of ['uid'] so in essence if I was to echo get_visitor_id() it would evaluate to "24".
Thanks for you help.
Cheers
try changing foreach() func to:
foreach($result as $res){
$res = $res->fetch_assoc();
$array['uid'] = $res['uid'];}
EDIT: in case of this didn't work then try while loop:
while($res = $result->fetch_assoc()){
$array['uid'] = $res['uid'];
}