I'm currently manually building an array.
$this->array_list = array('Alaska' => 'Alaska',
'Amanda' => 'Amanda',
'America' => 'America',
'Anthea' => 'Anthea',
'Arena' => 'Arena',
'Atlantis' => 'Atlantis'
);
I have a database that i can query this list from, My question is how do I create the array with key and value once getting the list from the query? Key and Value will always be the same. Using mysql and codeigniter.
Query DB for list, create two arrays and use combine? Has to be an easier way?
Here is what I ended up doing. Probably not the best way, feel free to give better way to do this.
$sofa_list2 = $this->get_media_model->get_sofas();
foreach ( $sofa_list2 as $k=>$v )
{
$newkey = $sofa_list2[$k]['collection_name'];
$sofa_list2[$k] ["$newkey"] = $sofa_list2[$k] ['collection_name'];
unset($sofa_list2[$k]['collection_name']);
}
$sofa_list2 = call_user_func_array('array_merge', $sofa_list2);
Related
I have an array that is returned from an API although some keys/values are not present all of the time.
example array
Array
(
[example0] => data
[example1] => data
[example2] => data
[example3] => data
)
Now if I use a query such as below
$dbh = $this->database->prepare("INSERT INTO table(example0, example1, example2, example3)VALUES(:example0, :example1, :example2, :example3)");
$dbh->execute(array(
"example0" => $data['example0'],
"example1" => $data['example1'],
"example2" => $data['example2'],
"example3" => $data['example3']
));
It will work fine. But when the API returns an array like
Array
(
[example0] => data
[example1] => data
[example3] => data
)
It will cause an error due to a value not being set, is there a way to just have it enter nothing into the column rather than throw an error? I am using a really big query for this so writing an if/else for each value would not be a good idea (in my opinion, for performance wise)
You have to check if the key is set and eventually is there is a value:
if(isset($array['your_key']) && !empty($array['your_key'])) { }
I cannot make it clear from your code but validate everything before you use it in a query.
[Edit] Example:
$keys = array('example1', 'example2', 'example3', 'example4');
$use_in_query = array();
foreach($keys as $key)
{
if(isset($array[$key]) && !empty($array[$key])) $use_in_query[$key] = $array[$key];
}
Now you can use the $use_in_query var in your query.
$dbh->execute($use_in_query);
[/Edit]
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 ;)
I have two arrays, which I can either do the simple approach, which is do a For Each loop on each array, and if one way is the method, accept it, or vice-versa, or is it possible to set values in an array with the same key value?
Like:
<?php
$Array = Array('UniqueValue' => 'Key',
'UniqueValue_2' => 'Key',
'DifferentValue' => 'Key_2'); // and etc...
?>
I could probably try trial and error, but another method would be somehow integrating the arrays and only reading the values I need?
Thanks for your guys' time.
ah, quick edit. I feel like someone's going to bring this up, so I read Nested array, get items with same key and I tried, but it's not working for me. It reads only the first value, and I'm not breaking the loop. If you want to see the code I'm working with, I'll gladly add it.
Actually, I found a better way to word this, so!
I need to iterate through each array value with the same key in a For Each loop.
Like so:
ForEach($Array as $Key){ // or $Key => $Value
If($Key == 'Key'){
Echo $Value;
}
}
<?php
$Array = Array(
0 => Array('Test', 'Testing', 'Tester'),
1 => Array('Test2'));
Print_R($Array[0]); // Array ( [0] => Test [1] => Testing [2] => Tester )
?>
Ah, I forgot about nesting arrays. Sorry about that, haha, but for anyone who would possibly need an answer, here you go.
Lets say I have an multidimensional string array:
.food = array(
'vegetable' => array(
'carrot' => 'blablue',
'potato' => 'bluebla',
'cauliflower' => 'blabla'
),
'Fruit' => array(
'apple' => 'chicken65',
'orange' => 'salsafood',
'pear' => 'lokkulakka'
)
);
is it possible to access the array by using index as numbers, instead of using the name of the key?
So for accessing chicken65 , I will type echo $food[1][0]; I don't want to use numbers as key, because its a big array and its more user-friendly if I use string as key and it will let me do for-loops on advanced level.
You can do foreach loops to achieve much the same thing as a typical for-loop.
foreach ($foods as $key => $value) {
//For the first iteration, $key will equal 'vegetable' and $value will be the array
}
$food[1][0] != $food[1]['apple'], so you cannot use numeric keys in this case.
try
$new_array = array_values($food);
however, variable can't start with .. It should start with $
you may want to try the function array_values but since you are dealing with multidemsional arrays, here is a solution posted by a php programmer
http://www.php.net/manual/en/function.array-values.php#103905
but it would be easier to use foreach instead of for.
You can use array_keys() on the array. The resulting array can be traversed via a for-loop and gives you the associative key.
I will show it to you for the first dimension:
$aTest = array('lol' => 'lolval', 'rofl' => 'roflval');
$aKeys = array_keys($aTest);
$iCnt = count($aKeys);
for($i = 0; $i < $iCnt; ++$i)
{
var_dump($aTest[$aKeys[$i]]);
}
You would need to do this for two dimensions but I would not recommend this. It is actually more obstrusive and slower than most other solutions.
I don't think there is something native to go this route.
And it does seem like you are trying to stretch array use a bit.
You should go OOP on this one.
Create a FoodFamilly object and a Food object in which you can store arrays if necessary and you'll be able to write a nice user-friendly code and add indices if needed.
OOP is almost always the answer :)
I have a simple query like this
SELECT hometeam.name AS hometeamName, hometeam.shortname AS hometeamShortName,
roadteam.name AS roadteamName, roadteam.shortname AS roadteamShortName,
smatch.startdate
FROM smatch
JOIN team hometeam
ON smatch.hometeamid = hometeam.uid
JOIN team roadteam
ON smatch.roadteamid = roadteam.uid
which be default returns a one dimensional array, like this:
array(5) {
["homeTeamName"] => "Brasil"
["homeTeamShortName"] => "BRA"
["roadTeamName"] => "Norway"
["roadTeamShortName"]=> "NOR"
["startdate"]=> "1309709700"
}
Question is, is there a mysql-way to let the result be a nested array, with a structure like the following?
result =>
hometeam =>
name
shortname
roadteam =>
name
shortname
startdate
And if not, is there a (php) post processing best practice to do this conversion?
Many thanks,
Robson
I don't think there's a way to directly get the result you want, but to generate that array after the query shouldn't be hard.
Something like this?
foreach($rows as $row) {
$resultArray[] = array(
'hometeam' => array(
'name' => $row['homeTeamName'],
'shortname' => $row['homeTeamShortName']
),
'roadteam' => array(
'name' => $row['roadTeamName'],
'shortname' => $row['roadTeamShortName']
),
'startdate' => $row['startdate']
);
}
MySQL (or any database) has no concept of arrays.
The only way I can think of is that you'd need to do it in a Stored Procedure and serialise the result in some way - essentially creating a serialised string... wich you'd then need to re-construct the array from.
However, would be better doing this in PHP to be honest, the gain from doing it in an SP will be minimal. Will be more efficient to query the main and then query within using loops PHP-side.
You have to fetch the result in PDO::FETCH_CLASS mode.
by specifying the __set()-method respectively you can store the result-field-data how ever you like.
This class should also extend ArrayAccess so you can access it like an array or have it return one.