I have a simple table with 2 colums: ID and Name. It looks like this:
License_ID License_Name
5 xxx
8 yyy
13 zzz
I want to write this table as an array, and I want to be able to find the license_id when license_name is provided. How can I write this array?
Edit: I can write the array the same as the answer nickb provided,
$array = array(
'xxx' => 5,
'yyy' => 8,
'zzz' => 13
);
but I want to have the license_id and license_name as key instead of using value of license_name as key.
Form an array with keys corresponding to the license name and values corresponding to the license ID, like so:
$sql = 'SELECT * FROM table'; // Optionally add a WHERE clause
$result = mysql_query( $sql);
$array = array();
while( $row = mysql_fetch_array( $result))
{
// Form the array
$array[ $row['License_Name'] ] = $row['License_ID'];
}
mysql_free_result( $result);
To omit the table and use a global variable, use the same technique:
$array = array(
'xxx' => 5,
'yyy' => 8,
'zzz' => 13
);
Now, to lookup the license ID, all you need is:
$license_id = 8;
$id = $array[ $license_id ]; // $id = 'yyy';
Edit: Here's an alternative way to represent the way in a more clear manner:
$array = array(
array(
'license_id' => 5,
'license_name' => 'xxx'
),
array(
'license_id' => 8,
'license_name' => 'yyy'
),
array(
'license_id' => 13,
'license_name' => 'zzz'
)
);
Then, to find the license_id when license_name is provided, loop to find your result:
$license_name = 'zzz';
foreach( $array as $entry)
{
if( $entry['license_name'] == $license_name)
{
echo 'Found ID of ' . $license_name . ' - ' . $entry['license_id'];
break;
}
}
OR, and even more direct way to prevent looping is to modify the above technique to have each sub-array contain the license_name as its key, like so:
$array = array(
'xxx' => array(
'license_id' => 5,
'license_name' => 'xxx'
),
'yyy' => array(
'license_id' => 8,
'license_name' => 'yyy'
),
'zzz' => array(
'license_id' => 13,
'license_name' => 'zzz'
)
);
Now, to find the license_id, you can do it directly once you know the license_name:
$license_name = 'zzz';
$license_id = $array[ $license_name ]['license_id'];
You know there is array_search out there,don't you? Personally I like to keep array keys as ids or numeric value.. so in your example $key=array_search('xxx',$myArr); (where id is the key and name is the value) http://php.net/manual/en/function.array-search.php
Related
I want to know that is there a way to insert certain elements of an array into a new array. I mean I have an array containing 10 objects. Each object has 3 or four fields for example id, name , age , username. now I want to insert the id's of all the objects into the new array with a single call.Is there anyway to do that.
$array = [
[0] => [
id =>
name =>
],
[1] = > [
id =>
name =>
]
]
and so on now I want to insert all the id's of all the object into a new array with a single call. Is there a way to do that?
Use array_map() function.
Here is your solution:-
$ids = array_map( function( $arr ){
return $arr["id"];
}, $arr );
echo '<pre>'; print_r($ids);
A basic foreach loop will do the job just fine
$firstArray = array(
array(
'id' => 1,
'name' => 'abc'
),
array(
'id' => 2,
'name' => 'def'
),
array(
'id' => 3,
'name' => 'gh'
)
);
$onlyIds = array();
$onlyKeys = array();
//To get the array value 'id'
foreach($firstArray as $value){
$onlyIds[] = $value['id'];
}
//To get the array keys
foreach($firstArray as $key => $value){
$onlyKeys[] = $key;
}
You could use array_walk which could be considered a "single call"
$array = array(0 => array('id', 'name', 'age'), 1 => array('id', 'name', 'age'));
array_walk($array, function($item, $key) {
// $key is 0 or 1
// $item is either id, name, age
});
You can use array_column.
$arr = [ ['id' => 1, 'username' => 'a'], ['id' => 2, 'username' => 'b'] ];
$ids = array_column($arr, 'id')
$ids == [1, 2]
I'm a beginer in PHP programming, i want to ask for my problem here.
Before, i get the PHP scripts from: https://github.com/VosCast/SHOUTcast-PHP-Stats
This is the code, how i get the array:
require_once 'vc_shoutcast.class.php'; // get stats
require_once 'vc_shoutcast_json_relay.class.php'; // produce json
$lists = array(
array(
'host' => 'host.net',
'port' => '9898'
),
array(
'host' => 'host.net',
'port' => '8787'
)
);
$i = 1;
foreach ($lists as $list => $radio) {
$vc_shoutcast = new vc_shoutcast( $radio['host'], $radio['port'], false );
$vc_shoutcast_json_relay = new vc_shoutcast_json_relay( $vc_shoutcast, 1, $cache = './stats_' . $i . '.json' );
$vc_shoutcast_json_relay->run( 'both' );
$i++;
}
This is the vc_shoutcast_json_relay.class.php ( $vc_shoutcast_json_relay->run( 'both' ); ) code:
foreach ($vars as $value) {
$data[$value] = $this->vc_shoutcast->$value;
}
var_dump( $data );
From the code above, I'll get two outputs array, like this:
Array(
[currentlisteners] => 2,
[maxlisteners] => 3,
[songtitle] => Some song title 2
)
Array(
[currentlisteners] => 12,
[maxlisteners] => 13,
[songtitle] => Some song title 2
)
How do I merge two arrays into one array become:
Array(
[0] => (
[currentlisteners] => 2,
[maxlisteners] => 3,
[songtitle] => Some song title 2
),
[1] => (
[currentlisteners] => 12,
[maxlisteners] => 13,
[songtitle] => Some song title 2
)
)
I know, i can merge 2 arrays with array_merge( $data ) or with something similiar functions, but it isn't works.
Thanks for your help.
Simplest way is to just create a new one with your existing arrays as the values:
$newArray = array($array1, $array2);
This is the same as this:
$newArray = array();
array_push($newArray, $array1);
array_push($newArray, $array2);
Or this:
$newArray = array();
$newArray[] = $array1;
$newArray[] = $array2;
Depending on your code, you might prefer to add your data to the main array using one of the last two methods as you go along, rather than trying to create the whole thing in one go at the end.
I have simple array
array(
array( 'id'=>5, 'something' => 2, 'dsadsa' => 'fsfsd )
array( 'id'=>20, 'something' => 2, 'dsadsa' => 'fsfsd )
array( 'id'=>30, 'something' => 2, 'dsadsa' => 'fsfsd )
)
How to create associative array by id field (or something else) from it in the right way?
array(
'5' => array( 'something' => 2, 'dsadsa' => 'fsfsd )
'20' => array( 'something' => 2, 'dsadsa' => 'fsfsd )
'30' => array( 'something' => 2, 'dsadsa' => 'fsfsd )
)
Something along these lines.
$new_array = array();
foreach ($original_array as &$slice)
{
$id = (string) $slice['id'];
unset($slice['id']);
$new_array[$id] = $slice;
}
#NikitaKuhta, nope. There is no slice function which returns a column of values in a 2D keyed table associated with a given key or column heading. You can use some of the callback array_... functions, but you will still need to execute a custom function per element so its just not worth it. I don't like Core Xii's solution as this corrupts the original array as a side effect. I suggest that you don't use references here:
$new_array = array();
foreach ($original_array as $slice) {
$id = (string) $slice['id'];
unset($slice['id']);
$new_array[$id] = $slice;
}
# And now you don't need the missing unset( $slice)
I have a multi-dimensional array that looks like this:
The base array is indexed based on category ids from my catalog.
$cat[category_id]
Each base array has three underlying elements:
['parent_id']
['sort_order']
['name']
I want to create a function that allows us to create a list of category_id's and names for a given parent_category_id in the correct sort order. Is this possible? Technically it is the same information, but the array is constructed in a weird way to extract that information.
Here is an example definition for the array:
$cat = array();
$cat[32]['parent_id']= 0;
$cat[32]['sort_order']= 1;
$cat[32]['name']= 'my-category-name1';
$cat[45]['parent_id']= 0;
$cat[45]['sort_order']= 0;
$cat[45]['name']= 'my-category-name2';
$cat[2]['parent_id']= 0;
$cat[2]['sort_order']= 2;
$cat[2]['name'] = "my-category-name3";
$cat[3]['parent_id']= 2;
$cat[3]['sort_order']= 1;
$cat[3]['name'] = "my-category-name4";
$cat[6]['parent_id']= 2;
$cat[6]['sort_order']= 0;
$cat[6]['name'] = "my-category-name5";
Assuming it's something of this sort:
$ary = Array(
0 => Array(
'parent_category_id' => null,
'sort_order' => 0,
'name' => 'my-category-name0'
),
1 => Array(
'parent_category_id' => 0,
'sort_order' => 1,
'name' => 'my-category-name1'
),
2 => Array(
'parent_category_id' => 0,
'sort_order' => 2,
'name' => 'my-category-name2'
),
3 => Array(
'parent_category_id' => null,
'sort_order' => 0,
'name' => 'my-category-name3'
),
4 => Array(
'parent_category_id' => 3,
'sort_order' => 0,
'name' => 'my-category-name4'
)
);
You can use a combination of a foreach and usort to achieve what you're going for.
// #array: the array you're searchign through
// #parent_id: the parent id you're filtering by
function getFromParent($array, $parent_id){
$result = Array();
foreach ($array as $category_id => $entry){
if ($entry['parent_category_id']===$parent_id)
$result[$category_id] = $entry;
}
usort($result,create_function('$a,$b','return ($a["sort_order"]>$b["sort_order"]?1:($b["sort_order"]<$a["sort_order"]?-1:0));'));
return $result;
}
var_export(getFromParent($ary,0));
EDIT Sorry, fixed some syntax errors. Tested, and works (at least to result in what I was intending)
EDITv2 Here's the raw output from the above:
array (
0 =>
array (
'parent_category_id' => 0,
'sort_order' => 1,
'name' => 'my-category-name1',
),
1 =>
array (
'parent_category_id' => 0,
'sort_order' => 2,
'name' => 'my-category-name2',
),
)
(Used var_export just for you #FelixKling)
EDITv3 I've updated my answer to go along with the OP's update. I also now make it retain the original "category_id" values in the result array.
First you create an empty array, it will be used to store your result.
$result = array();
You need to iterate through your initial array, you can use foreach().
Then, given your parent_category_id simply use an if statement to check whether it's the given id or not.
If it is, just construct and push your result to your $result array.
Use any of the sort functions you like
Use the magic return $result;
You're done.
function returnSortedParents($categories, $target_parent){
$new_list = array();
foreach($categories as $index => $array){
//FIND ONLY THE ELEMENTS MATCHING THE TARGET PARENT ID
if($array['parent_category_id']==$target_parent){
$new_list[$index = $array['sort_order'];
}
return asort($new_list); //SORT BASED ON THE VALUES, WHICH IS THE SORTING ORDER
}
I have an array of items:
array(
[0] => array(
'item_no' => 1
'item_name' => 'foo
)
[1] => array(
'item_no' => 2
'item_name' => 'bar'
)
) etc. etc.
I am getting another array from a third party source and need to remove items that are not in my first array.
array(
[0] => array(
'item_no' => 1
)
[1] => array(
'item_no' => 100
) # should be removed as not in 1st array
How would I search the first array using each item in the second array like (in pseudo code):
if 'item_no' == x is in 1st array continue else remove it from 2nd array.
// Returns the item_no of an element
function get_item_no($arr) { return $arr['item_no']; }
// Arrays of the form "item_no => position in the array"
$myKeys = array_flip(array_map('get_item_no', $myArray));
$theirKeys = array_flip(array_map('get_item_no', $theirArray));
// the part of $theirKeys that has an item_no that's also in $myKeys
$validKeys = array_key_intersect($theirKeys, $myKeys);
// Array of the form "position in the array => item_no"
$validPos = array_flip($validKeys);
// The part of $theirArray that matches the positions in $validPos
$keptData = array_key_intersect($theirArray, $validPos);
// Reindex the remaining values from 0 to count() - 1
return array_values($keptData);
All of this would be easier if, instead of storing the key in the elements, you stored it as the array key (that is, you'd be using arrays of the form "item_no => item_data") :
// That's all there is to it
return array_key_intersect($theirArray, $myArray);
You can also do:
$my_array =array(
0 => array( 'item_no' => 1,'item_name' => 'foo'),
1 => array( 'item_no' => 2,'item_name' => 'bar')
);
$thrid_party_array = array(
0 => array( 'item_no' => 1),
1 => array( 'item_no' => 100),
);
$temp = array(); // create a temp array to hold just the item_no
foreach($my_array as $key => $val) {
$temp[] = $val['item_no'];
}
// now delete those entries which are not in temp array.
foreach($thrid_party_array as $key => $val) {
if(!in_array($val['item_no'],$temp)) {
unset($thrid_party_array[$key]);
}
}
Working link
If your key is not actually a key of your array but a value, you will probably need to do a linear search:
foreach ($itemsToRemove as $itemToRemove) {
foreach ($availableItems as $key => $availableItem) {
if ($itemToRemove['item_no'] === $availableItem['item_no']) {
unset($availableItems[$key]);
}
}
}
It would certainly be easier if item_no is also the key of the array items like:
$availableItems = array(
123 => array(
'item_no' => 123,
'item_name' => 'foo'
),
456 => array(
'item_no' => 456,
'item_name' => 'bar'
)
);
With this you could use a single foreach and delete the items by their keys:
foreach ($itemsToRemove as $itemToRemove) {
unset($availableItems[$itemToRemove['item_no']]);
}
You could use the following to build an mapping of item_no to your actual array keys:
$map = array();
foreach ($availableItems as $key => $availableItem) {
$map[$availableItems['item_no']] = $key;
}
Then you can use the following to use the mapping to delete the corresponding array item:
foreach ($itemsToRemove as $itemToRemove) {
unset($availableItems[$map[$itemToRemove['item_no']]]);
}