using in_array() with keys and values in arrays? - php

Let's say I have an array
$array = array(
'username' => "username",
'location' => "location",
'other' => "other");
This array can hold data for many users, so there could be different values for each 'username', 'location', and 'other' fields. How can I use in_array() or another function to determine if a specific username exists in the array already? Because what if a user has a username like "nyc" and a location of "nyc" and I do
in_array("nyc", $array);
How exactly should something like this be approached?
Thank you.

To achieve something that I think is what you want, you can make an array of associative arrays that have the same keys.
<?php
// This syntax will work only on PHP 5.4
$a=[["name"=>"john","age"=>25],["name"=>"philip","age"=>110]];
print_r(array_filter($a, function($item) {return $item["name"] === "john"; }));
?>
Outputs:
Array
(
[0] => Array
(
[name] => john
[age] => 25
)
)
If you just wanted to know if a person named John was in the list, you can just use sizeof/count on the returned array.
This will allow you to have any number of duplicates, and you don't need to specify any keys. Check out the functions: array_filter, array_reduce, array_map. With all of these, you can process your list using closures like in my example above.
Instead of using associative arrays in your array, you could have objects too. Objects are more heavyweight, and need initialization and stuff, so it is grotesque for using them for tiny static (hardcoded) lists. But they may come handy when your data structures grow and you want to make sure every list item has a certain property (the constructor of the class could ensure that everything is initialized). But the good thing is that filter, reduce and map would still work. The "$item" would then be your object.

$users = array( 'user_id' => array('username' => "username",
'location' => "location",
'other' => "other");
user_id is their NUMBER user_id
So you then call $users['####']['username'];
IE:
$users = array( '1' => array('username' => 'Jim',
'location' => 'Florida',
'other' => "other"),
'2' => array('username' => 'Jane',
'location' => 'Maryland',
'other' => "Grapes"));
Then use array_keys() to search for their user_id

Related

How to get values of array 1 and array 2 based on array index of array3 in laravel/php? [duplicate]

I wrote this function to get a subset of an array. Does php have a built in function for this. I can't find one in the docs. Seems like a waste if I'm reinventing the wheel.
function array_subset($array, $keys) {
$result = array();
foreach($keys as $key){
$result[$key] = $array[$key];
}
return $result;
}
I always want this too. Like a PHP version of Underscore's pick.
It's ugly and counter-intuitive, but what I sometimes do is this (I think this may be what prodigitalson was getting at):
$a = ['foo'=>'bar', 'zam'=>'baz', 'zoo'=>'doo'];
// Extract foo and zoo but not zam
print_r(array_intersect_key($a, array_flip(['foo', 'zoo'])));
/*
Array
(
[foo] => bar
[zoo] => doo
)
*/
array_intersect_key returns all the elements of the first argument whose keys are present in the 2nd argument (and all subsequent arguments, if any). But, since it compares keys to keys, I use array_flip for convenience. I could also have just used ['foo' => null, 'zoo' => null] but that's even uglier.
array_diff_key and array_intersect_key are probably what you want.
There is no direct function I think in PHP to get a subset from an array1 with compare to another array2 where the values are the list of key name which we fetch.
Like: array_only($array1, 'field1','field2');
But this way can be achieved the same.
<?php
$associative_array = ['firstname' => 'John', 'lastname' => 'Smith', 'DOB' => '2000-10-10', 'country' => 'Ireland' ];
$subset = array_intersect_key( $associative_array, array_flip( [ 'lastname', 'country' ] ) );
print_r( $subset );
// Outputs...
// Array ( [lastname] => Smith [country] => Ireland );

What multi dimensional array needed to store 3 levels of information?

I'm working on a PHP script to hold a lot of information.
Lets try to explain our situation!
I have actually 33 different stations.
For each of that 33 stations I have 5 different categories.
And for each of that 33 stations with each 5 different categories i have 37 different values per category.
Do I need an 2d of 3d array for store this information in it ?
Thanks you!
Something like this will work, just add more data as needed:
$station_array =
array(
'station1' => array(
'cat1' => array ('val1','val2','val3'),
'cat2' => array ('val1','val2','val3'),
'cat3' => array ('val1','val2','val3')
),
'station2' => array (
'cat1' => array ('val1','val2','val3'),
'cat2' => array ('val1','val2','val3'),
'cat3' => array ('val1','val2','val3')
),
'station3' => array (
'cat1' => array ('val1','val2','val3'),
'cat2' => array ('val1','val2','val3'),
'cat3' => array ('val1','val2','val3')
)
);
Sounds like a job for a relational database!
But you're correct in your initial assumption. You will need a 3-dimensional array to hold your information because your data has 3 tiers: the stations, the categories, and the values.
A php array will be fine for this
$MyArray = array('Station1' => array('Category1' =>
array('Value1'=> 1000,'Value2'=> 1001),
'Category2' => array('Value1' => 2332)), etc...
'Station2' => array('Category1' =>
array('Value1'=> 1000,'Value2'=> 1001),
'Category2' => array('Value1' => 2332)), etc
etc
);
Once you pass more than two dimensions in an associative array, it's good to start considering using objects to store your information. Objects make it a lot easier to understand how things are organized, they can enforce validation restrictions on your data (make sure it's in the form it should be), and you can call functions on the data to manipulate it (instead of having random external functions manipulating your entire array). An example would be:
class CategoryValue {
var $val; // your value
function __construct($val) {
$this->val = $val;
}
}
class Category {
var $values = array(); // an array of CategoryValue objects
function addValue(CategoryValue $val) {
$this->values[] = $val;
}
}
class Station {
var $categories = array(); // an array of Category objects
function addCategory(Category $category) {
$this->categories[] = $category;
}
}
well, all depends on how you want to acheive, if you dont need to loop through the values, but you just want to store data and alway know whay you want to get, you could use hashes for that, the table would look like:
$data = array(
md5('StationX'.'CategoryY'.'PropertyZ') => 'ValueU',
md5('StationA'.'CategoryB'.'PropertyC') => 'ValueQ'
);
This way you can get the data right away and dont have to bother to check if you initialised CategoryB array for StationA when you want to add value for PropertyZ
php stores associative arrays as hastables technically
... thats all if you really insist on not using databases ;)

How to custom sort array indexes in php?

I have a multidimensional array or arrays which I also use in my configuration file. The file is also manually edited so I want some of the keys to have fixed position. The code reads configuration file with this array, modifies, insert keys etc and then saves it back. On save I sort the keys but now I found that it is not good enough.
Is there any way to have
the key 'full_name' always as the first key
the key 'version' as second one
and the rest of the keys to be sorted alphabetically?
Sample of the array....
array (
'skroob' =>
array (
'ssh' => 'skroob',
'codebase_path' => '/srv/www/htdocs/imacs/radek/4.0.1',
'ssh_status' => 'ok',
'version' => '4.0.1',
'ssh_last_access' => '2012-Feb-17 10:07:26',
'edu_url' => 'https://testing/imacs/radek/4.0.1',
'full_name' => 'skroob 4.0.1',
),
'testing' =>
array (
'full_name' => 'My beautiful testing server (trunk)',
'version' => 'trunk',
'ssh' => 'testing',
'codebase_path' => '/srv/www/htdocs/imacs/radek/trunk',
'ssh_last_access' => '2012-Feb-17 10:07:26',
'ssh_status' => 'ok',
),
)
Here's one way. It sorts the array alphabetically, by key. Then it reverses the array and unsets the full_name and version keys. Then it adds those keys again, so they get placed at the end of the array. Lastly, it reverses the array again. Kinda hacky but I'm not sure there's a much better way to do what you're asking.
ksort($arr['skroob']);
$arr['skroob'] = array_reverse($arr['skroob']);
$version = $arr['skroob']['version'];
$full_name = $arr['skroob']['full_name'];
unset($arr['skroob']['full_name'], $arr['skroob']['version']);
$arr['skroob']['version'] = $version;
$arr['skroob']['full_name'] = $full_name;
$arr['skroob'] = array_reverse($arr['skroob']);
Another solution is to use uksort and write a small callback function. That would probably look a bit more professional.

Reorganize an array by 'id' index of nested arrays

I have an array that looks like this:
Array([0]=>Array([id]=>7 [name]=foo) [1]=>Array([id]=>10 [name]=bar) [2]=>Array([id]=>15 [name]=baz))
Each index contains an another array with various elements including an 'id'. I would like to "go up" a level, such that my top-level array is indexed by the ID element of the corresponding nested arrays, but that index still contains an array with all of the elements that were in the sub arrays?
In other words, how can I use PHP to turn the above array into this:
Array([7]=>Array([id]=>7 [name]=foo) [10]=>Array([id]=>10 [name]=bar) [15]=>Array([id]=>15 [name]=baz))
What you need to do here is extract the ids from each sub-array in your input. If you have these as an array of ids, you are just an array_combine call away from re-indexing your original array to use these ids as the keys.
You can produce such an array of ids using array_map, which leads to:
// input data
$array = array(array('id' => '7', 'name' => 'foo'),array('id' => 10, 'name' => 'bar'));
// extract ids from the input array
$ids = array_map(function($arr) { return $arr['id']; }, $array);
// "reindex" original array using ids as array keys, keep original values
$result = array_combine($ids, $array);
print_r($result);
The syntax I 've used for the anonymous function (first argument to array_map) requires PHP >= 5.3, but you can achieve the same (although a bit less conveniently) with create_function in any PHP version you 'd not be ashamed of using.
See it in action.
In modern, supported versions of PHP, this whole task can be achieved with array_column() alone.
Using null as the second parameter will leave the rows unchanged.
Using id as the 3rd parameter will assign those columnar values as the new first level keys. Be aware that if these columnar values are not unique, subsequently encountered duplicates will overwrite previously encountered rows with the same id value -- this is because keys cannot be duplicates on a given level in an array.
DO NOT bother calling array_combine(), it is simply unnecessary/indirect.
Code: (Demo)
$array = [
['id' => 7, 'name' => 'foo'],
['id' => 10, 'name' => 'bar'],
['id' => 15, 'name' => 'baz'],
];
var_export(
array_column($array, null, 'id')
);
Output:
array (
7 =>
array (
'id' => 7,
'name' => 'foo',
),
10 =>
array (
'id' => 10,
'name' => 'bar',
),
15 =>
array (
'id' => 15,
'name' => 'baz',
),
)
Try this:
$newArray = array();
foreach($oldArray as $key => $value) {
$newArray[$value['id']] = $value;
}
Since PHP 5.5.0, you can shorten the code by using array_column() instead of array_map().
$result = array_combine(array_column($array, 'id'), $array);

Replace array key integers with string

$string = "php, photoshop, css";
I'm producing an array from the comma separated values above using the str_getcsv() function:
$array = str_getcsv($string);
Result:
Array ( [0] => php [1] => photoshop [2] => css )
How can I replace the key integers with a string tag for all elements like seen below?
Array ( [tag] => php [tag] => photoshop [tag] => css )
Edit: if not possible what alternative can I apply? I need the array keys to be identical for a dynamic query with multiple OR clauses
e.g.
SELECT * FROM ('posts') WHERE 'tag' LIKE '%php% OR 'tag' LIKE '%photoshop% OR 'tag' LIKE '%css%'
I'm producing the query via a function that uses the array key as a column name and value as criteria.
That is not possible. You can have only one item per key. But in your example, the string "tag" would be the key of every item.
The other way arround would work. So having an array like this:
array('php' => 'tag', 'photoshop' => 'tag', 'css' => 'tag');
This might help you, if you want to save the "type" of each entry in an array. But as all the entries of your array seems to be from the same type, just forget about the "tag" and only store the values in a numeric array.
Or you can use a multidimensional array within the numeric array to save the type:
array(
0 => array( 'type' => 'tag', 'value' => 'php' ),
1 => array( 'type' => 'tag', 'value' => 'photoshop' ),
2 => array( 'type' => 'tag', 'value' => 'css' )
);
But still using just an numeric array should be fine if all the entries have the same type. I can even think of a last one:
array(
'tag' => array('php', 'photoshop', 'css')
);
But even if I repeat myself: Just use an ordinary array and name it something like $tag!
BTW: explode(', ', %string) is the more common function to split a string.
To build SQL statement you might do something like this:
// ... inside you build function
if(is_array($value)){
$sql .= "'".$key."' LIKE '%."implode("%' OR '".$key."' LIKE '%", $value)."%'";
} else {
$sql .= "'".$key."' LIKE '%".$value."%'";
}
This might look confusing but it's much cleaner than runnig into two foreach-loops building the query.
That won't work. Your array keys have to be unique, or subsequent additions will simply overwrite the previous key.
As the others said, keys have to be unique. Otherwise, which element should be returned if you access $arr['tag']? If you now say "all of them", then create a nested array:
$array = array();
$array['tag'] = str_getcsv($string);
The value $array['tag'] will be another array (the one you already have) with numerical keys. This makes, because you have a list of tags and lists can be represented as arrays too.
Understanding arrays is very important if you want to work with PHP, so I suggest to read the array manual.
Assuming you know the size of your array beforehand
$tags = array("tag1","tag2","tag3");
$data = array("php","photoshop","css");
$myarray = array();
for ($i=0; $i<count($data); $i++) {
$myarray[$i] = array($data[$i], $tags[$i]);
}
Then
echo $myarray[0][0] . ", " . $myarray[0][1];
Outputs:
php, tag1

Categories