Matching multiple values against an array - php

My problem is:
I have an array called $ownerArray that another array need to check against and if a key exists in both arrays display the value of the matching key. $ownerArray is populated by a database so i can't just write an ir statement within a if statement.
$ownerArray will look like this:
$ownerArray = array(0 =>'Name0',1 =>'Name1',2 =>'Name2',3 =>'Name3');
Then I have another array called $Users that has a various number of values depending on what the user selects, so $Users could look like this:
$Users = '1,2'
or Like this:
$Users = '1,3'
$Users is never the same.
But I need the $value of $ownerArray to display if any of the values integers of $Users match any $key of $ownerArray
Example:
foreach($ownerArray as $key => $value)
{
if(in_array($key,array($Users)))
{
print $value;
}
}
This method stops at the fist match and displays the correct name. The loop doesn't continue printing if more values match.
What im looking for is if $Users = '1,3' my for loop will print Name1 and Name3 from the $ownerArray.
Thanks for the help!
ps i know i could use if($key==1 || $key ==2) but that will not work for this case.

$merged = array_flip(array_intersect(array_flip($owners), explode(',', $users)));

something like this could work
<?php
$ownerArray = array(0 =>'Name0',1 =>'Name1',2 =>'Name2',3 =>'Name3');
$users = explode(',','1,2');
if(count($users) > 0){
foreach($users as $user){
if($key = array_search($user,$ownerArray)){
echo $key;
}
}
}
?>

Just invert your logic. You are actually wanting to cycle through your users, and print something if they exist in the owner array, not the other way around. (Apologies if this code is slightly off, but you get this idea.)
foreach($Users as $value)
{
if(in_array($value,array($ownerArray)))
{
print $ownerArray[$value];
}
}

Related

Get specific array value where another value is "1"?

I have an array that looks like this:
Id = "ADA001"
Stock: 15
The array has about 1700 records that looks the same, how would I search the array for the ID 1 and return the stock?
Edit: I will need to access the stock of each one of these 17000 records
Edit: I have been getting some help from Daniel Centore, he told me to set an arrays primary key to the id of the item and that it is equal to the stock, but I can't get it to work.
I am currently getting the data from an MySQL database and I store it in an array, like so:
$data[] = array();
$getdisposabletest = mysqli_query($connect, "Select id, disposable FROM products");
while ($z = mysqli_fetch_array($getdisposabletest)) {
$data = $z;
}
Now when I use Daniels code that looks like this:
$myMap = [];
foreach($data as $item) {
$myMap[$item['id']] = $item['disposable'];
}
It doesn't return anything when I try to echo my product with the ID "ADA001"
echo $myMap["ADA001"];
Also when I do "count($mymap)" it says its 2 records big, when it should be muuuch larger than that?
Thanks for help
I would use array_filter. Return the result of a comparitor.
$results = array_filter($targetArray, function($el) {
return $el === 1;
});
Edit: Now that it has been made clear that the OP wants to query from thousands of items, the correct way to do this is to make the Id the key to a map in PHP, like this:
$myMap = [];
foreach($array as $item) {
$myMap[$item['Id']] = $item['Stock'];
}
Now, whenever you want to access item '12', simply use $myMap['12'].
The reason this is faster is because of something called algorithmic complexity. You should read about Big-O notation for more info. Essentially, the first operation here is on the order of n and then looping through each of the items that comes out is on the order of n*log(n), so the final result is on the order of n*log(n) which is the best you'll be able to do without more information. However, if you were only accessing one element, just accessing that one element via MySQL would be better because it would be on the order of log(n), which is faster.
Edit 2: Also notice that if you were to access mutliple fields (ie not just the stock) you could do the following:
$myMap = [];
foreach($array as $item) {
$myMap[$item['Id']] = $item;
}
And simply access item 12's stock like this: $myMap['12']['stock'] or its name like this: $myMap['12']['name'].
You would do something like this.
$newArray=[];
foreach($array as $item){
if($item['Id'] === 1){
$newArray[] = $item;
}
}
$stockArray = array_column($newArray,'Stock');

update element in php foreach

I know this should be very simple, but boy I'm making a mess of it... would be great if someone could point me in the right direction.
I've got an array which looks like this:
print_r($request_attributes['length']);
Array
(
[0] => 28.00000
[1] => 18.00000
)
and am trying to modify like so:
if(is_array($request_attributes['length'])) {
$request_attributes['length'] = $request_attributes['length'][0];
print($request_attributes['length']);
$request_attributes['length'] = $request_attributes['length'][1];
print($request_attributes['length']);
}
which gives the correct output in the first update, but the second item outputs an '8'. I've tried the above in both a for and foreach which results in similar output for both this and the other two arrays ( width(8) and height(0) - they should result in 18.00000 and 13.00000 respectively ). So I guess I really have two questions:
1. How do I update this(these) element(s)?
2. Where are the funny outputs actually coming from?
If anyone can help, I'd really appreciated it.
Just have a look at this. Your problem is, that you override you variable and in the second step $request_attributes['length'] is a string. Just define another var for your values.
$request_attributes['length'] = [
28.000,
18.000
];
$attributes = array();
if (is_array($request_attributes['length'])) {
foreach ($request_attributes['length'] as $value) {
$attributes[] = $value;
}
}
As you see $attributes will contain all values of your $request_attributes['length'] array and will not be overwritten.
Define araay as below
$val=array([0]=>"18.000",[1]=>13.000)
then use
if(is_array($request_attributes['length'])) {
$request_attributes['length'] = $val;
print_r($request_attributes['length']);
$request_attributes['length'] = $val;
print_r($request_attributes['length']);
}
Previously your array doesnt have any name.
Your print will only return Just array not the values
use
print_r($request_attributes['length']) ;
instead

Replace single value in multidimensional array

I am trying to unset/remove then replace/update a single value from a post meta field, but my code for array_push() and unset() are removing all of the values from each array.
Here are the two halves of the code I am currently using.
First, to find and remove the old value:
$ID = $_GET["post_id"];
$old = $entry["85"];
$old_meta = array();
$old_meta = get_post_meta($old,'_website',false);
if(in_array($ID, $old_meta[current][items])){
unset($old_meta[current][items][$ID]);
}
update_post_meta($old,'_website',$old_meta);
Second to append the new value to the appropriate location:
$port = $entry["24"];
$new_meta = array();
$new_meta = get_post_meta($port,'_website',false);
$new_meta[content][items] = array();
array_push($new_meta[content][items],$ID);
update_post_meta($port,'_website',$new_meta);
It works to unset and insert the correct value, but any other values that were there (for both updating or unsetting) in the meta[current][items] array are removed.
Before running any functions the array looks like this:
pastie.org/8112933
After I run array_push it looks like this:
pastie.org/8112956
After unset it looks like this:
pastie.org/8112974
in_array checks to see if an element in array has a value equal to that value, not a key. So you would need to do something like this:
if(in_array($ID, $old_meta['current']['items'])){
foreach($old_meta['current']['items'] as $key => $val) {
if($val == $ID) {
unset($old_meta['current']['items'][$key]);
}
}
}
If you need to check for a key not a value just replace in_array() with array_key_exists() and keep your current code.

fetch data from model that is called in loop

I have a controller function in CodeIgniter that looks like this:
$perm = $this->job_m->getIdByGroup();
foreach($perm as $pe=>$p)
{
$pId = $p['id'];
$result = $this->job_m->getDatapermission($pId);
}
$data['permission'] = $result;
What I need to do is list the data in the result in the view, but I get only the last value while using this method. How can I pass all the results to the view?
Store it in an array. Like this:
foreach($perm as $pe=>$p){
$result[] = $this->job_m->getDatapermission($p['id']);
}
Because $result is not an array...
try this:
$result=array();
foreach($perm as $pe=>$p)
{
$pId = $p['id'];
$result[] = $this->job_m->getDatapermission($pId);
}
$data['permission'] = $result;
Note:
My answer uses a counter to enable the display of a single group result when needed.
Guessing from your need to loop and display the value of $result, possibly, it is an array or object returned by $query->result(). Things could be a bit complex.
Example: if $perm is an array of 5 items( or groups), the counter assigns keys 1 - 5 instead of 0 - 4 as would [] which could be misleading. Using the first view example, you could choose to display a single group value if you wants by passing it via a url segment. Making the code more flexible and reusable. E.g. You want to show just returns for group 2, in my example, $result[2] would do just that else next code runs. See my comments in the code.
$perm = $this->job_m->getIdByGroup();
$counter = 1;
foreach($perm as $pe=>$p)
{
$pId = $p['id'];
$result[$counter] = $this->job_m->getDatapermission($pId);
$counter++;
}
$data['permission'] = $result;
As mentioned above Note:
I Added a Counter or Key so you target specific level. If the groups are:
Men, Women, Boys, Girls, Children; you'd know women is group two(2) If you desire to display values for just that group, you don't need to rewrite the code below. Just pass the group key would be as easy as telling it by their sequence. To display all the loop without restrictions, use the second view example. To use both, use an if statement for that.
###To access it you could target a specific level like
if(isset($permission)){
foreach($permission[2] as $key => $value){
echo $value->columnname;
}
###To get all results:
foreach($permission as $array){
foreach($array as $key => $value){
echo $value->columnname;
}
}
}

php arrays: search for matching values in a table and replace with array keys

Please i want to loop through my table and compare values with an array in a php included file. If there is a match, return the array key of the matched item and replace it with the value of the table. I need help in returning the array keys from the include file and comparing it with the table values.
$myarray = array(
"12aaa"=>"hammer",
"22bbb"=>"pinchbar",
"33ccr"=>"wood" );
in my loop in a seperate file
include 'myarray.inc.php';
while($row = $db->fetchAssoc()){
foreach($row as $key => $val)
if $val has a match in myarray.inc.php
{
$val = str_replace($val,my_array_key);
}
}
So in essence, if my db table has hammer and wood, $val will produce 12aaa and 3ccr in the loop. Any help? Thanks a lot
You are looking for array_search which will return the key associated with a given value, if it exists.
$result = array_search( $val, $myarray );
if ($result !== false) {
$val = $result;
}
your array should look like
$myarray = array(
"hammer"=>"11aaa",
"pinchbar"=>"22bbb",
"wood"=>"33ccr" );
and code
if (isset($myarray[$key])){
//do stuff
}
I think you need the function in_array($val, $myarray);
If you don't want or can't change $myarray structure like #genesis proposed, you can make use of array_flip
include 'myarray.inc.php';
$myarray = array_flip($myarray);
while($row = $db->fetchAssoc()) {
foreach($row as $key => $val) {
if (isset($myarray[$val])) {
// Maybe you should use other variable instead of $val to avoid confusion
$val = $myarray[$val];
// Rest of your code
}
}
}

Categories