Is it possible to concatenate two values in an array together? - php

I’m new to PHP so this might be a very long questions. First of all I can’t normalise the database the way it has been designed it has to be kept like this. I’ll explain the scenario first: I have locations on a map, those locations can have as many products attached to them as possible. My issue is that I want to concatenate two values together in an array to make them into a string so I can store it in the db and then use it.
I’m having issues with a particular record, this record 1234 is causing me issues. As it has two Ratings attached to it but I need to concatenate them and put them into another array so I can store in my database in a particular field as strings instead of separate ints.
Below is the code, as you’ll see I did a if statement inside the code I want to use to debug what is happening in that particular record.
$ratingString = array();
$rating = 0;
foreach( //not sure if this foreach is related to the question)
if(true == isset($ratingString[$location[‘id’]])){
echo ‘in set’;
$ratingString[$location[‘id’]][‘ratingString’] = strval( $ratingString[$location[‘id’]][‘ratingString’]).’,’.$rating;
}else {
if($location[‘id’] == 1234){
echo ‘not in set’
$ratingString[$location[‘id’]][‘ratingString’] = $rating;
Print_r($ratingString);
} }
When I debug this, it shows me two variables in rating string.
Not in set
string() “ratingString”
array(1){
[1234] =>
array(1) {
[“ratingString”] =>
int(2)
}
}
Not in set
string() “ratingString”
array(1){
[1234] =>
array(1) {
[“ratingString”] =>
int(3)
}
}
So what I need help with, is how could I concatenate the two so that it would be [ratingString] => string 2,3 and how would I change my code so that it would work for all my locations and not just this particular record.

Related

Get value out of Array

I am trying to get a certain value out of an array.
Example of the array is:
array(2) {
["error"]=>
array(0) {
}
["result"]=>
array(1) {
["open"]=>
array(1) {
["12345-AAAAA-66AAKK"]=>
array(14) {
["inf"]=>
Usually when I want a certain value I would use:
$datawanted=$data[result][open][value];
However, in this case the first array is a variable that always changes (12345-AAAAA-66AAKK), I need to find the value of that.
I tried getting this with reset() and key[0] but this not give the wanted result.
Is there a way to get the output of the first element in the result array?
You can use array_search: http://php.net/manual/de/function.array-search.php
Example:
foreach ($array['result']['open'] as $dynamicKey => $item) {
if ($key = array_search('Value you are looking for', $item) {
$datawanted=$array['result']['open'][$dynamicKey][$key];
}
}
$data[result][open] is not a correct way to access array items.
The token result looks like a constant. PHP searches for a constant named result, cannot find one and triggers a notice. Then it thinks "I guess the programmer wanted to write 'result' (a string, not a constant). I'll convert it as string to them." and uses 'result' instead.
It works but it's a horrible practice. It dates from the prehistory of PHP, 20 years ago and it's not recommended.
After you fix your code to correctly denote the keys of an array, the next step is to pick one of the many PHP ways to access values in the array.
You can get the first value of an array without knowing its key ($data['result']['open']['12345-AAAAA-66AAKK']) by using the function reset():
$datawanted = reset($data['result']['open']);
Or you can use the function array_values() to get only the values of the array (the keys are ignored, the returned array have the values indexed from zero) then your desired data is at position 0 on this array:
$values = array_values($data['result']['open']);
$datawanted = $values[0];
Another option, if you don't need to keep $data for further processing, is to use the PHP function array_shift() to remove the first value from the array and return it. Be warned that this function modifies the array it receives as argument:
$datawanted = array_shift($data['result']['open']);
If you need to process all the values of $data['result']['open'] (and you probably do) then the best way is to use the foreach PHP statement. It allows you to access both the key and the value of each element of the array:
foreach ($data['result']['open'] as $key => $value) {
// $key is '12345-AAAAA-66AAKK'
$datawanted = $value;
}

Splitting up an array formed by an api in PHP

I'm working on some stat tracking code for a game (yes, it's runescape. sue me).
I want to pull information from the high scores using an api which produces an array looking like this (captured using print_r)
Array
(
[getHiscore] => Array
(
[overall] => Array
(
[rank] => 61995
[lvl] => 2273
[totalxp] => 193310588
)
[attack] => Array
(
[rank] => 93406
[lvl] => 97
[totalxp] => 11747494
)
...and so on.
My question is how can i take what this api gives me and place it into a database table; I want to get an array such as this for a particular user and update their stats with it.
Would i use explode? It seems like the right idea to me but how would i actually use it to split the separate numbers and words?
My database is not totally realised yet, however each record will include a user name and then the level and total xp in each of 27 "skills". This almost certainly not best practice for database design but i'm as novice as they come so it's the best i can do.
You don't need to explode. It's an array and therefore it's already exploded. You need to iterate through it to build meaningful queries.
I'm not familiar with runescape so I don't know if your example is showing just the relevant fields of you need to discard some part. If it's the former, then you should try something like
$query="insert into stats_table (description, rank, lvl, totalexp) values (:description, :rank, :lvl, :totalext);";
$Statement = $DBConn->prepare($query);
foreach($fullArray as $description=>$subArray) {
$Statement->bindValue(':description',$description, PDO::PARAM_STR);
foreach($subArray as $key=>$value) {
$Statement->bindValue($key,$value, PDO::PARAM_STR);
}
$Statement->execute();
}
That will insert two rows containing
overall 61995 2273 193310588
attack 93406 97 11747494
PD: $DBConn is a PDO connection instance to whatever DB engine you're using.
Let's say this is all stored in the variable $ary:
$ary['getHiscore']['overall']['rank'] = 61995;
$ary['getHiscore']['overall']['lvl'] = 2273;
$ary['getHiscore']['overall']['totalxp'] = 193310588;
$ary['getHiscore']['attack']['rank'] = 93406;
$ary['getHiscore']['attack']['lvl'] = 97;
$ary['getHiscore']['attack']['totalxp'] = 11747494;
So, to get those values, it's:
$attackLevel = $ary['getHiscore']['attack']['lvl'];
If you
echo $attackLevel;
it would be 97.
Just pull the arrays out with a foreach loop and write some sql to insert the data. I don't know anything about your DB so if you want help there update your question please.
Simplest way to do this:
foreach($highscores as $highScoreType => $highScoreValues){
$rank = $highScoreValues['rank'];
$lvl = $highScoreValues['lvl'];
$totalXp = $highScoreValues['totalxp'];
//then it's up to you to put it into a table somehow.
}
$highScoreType will contain the values 'overall','attack',etc
This format of the foreach loop is extremely handy when iterating over an associative array (hash map/hash table, which is actually what all PHP arrays are underneath) will allow you to not only grab the value of the current pointed to entry, but also the key for that entry.
So, assume we have a single entry hashmap with key 'foo' and value 'bar'. If I want to show 'bar' I would simple
echo $map['foo'];//will output 'bar'
and if I put this into the above type of foreach loop
foreach($map as $fooKey => $barValue) {
echo $fooKey;//outputs 'foo'
echo $barValue;//outputs 'bar'
}

need a simple programming logic solution..

I am working on a CakePHP 2.x but right now my question has nothing to do with the syntax. I need a solution for this problem:
I have a table named messages in which there is a field name mobile numbers. The numbers are in this format:
12345678 and +9112345678 .. so they are both the same. The only difference is that in one number the country code is missing.
So I do this query in the database:
select the distinct numbers from messages tables..
Now it is taking these both numbers as distinct. But what I want is to take these both numbers as one.
How can I do this? In my DB there are several numbers with different country codes. Some have a country code and some don't, but I want to take both as one. The one in country code and the other without code. How can this be done?
At times now I have an array in which all the distinct numbers are stored. In this array there are numbers like this:
12345678 +9112345678
So now I don't know how to make a logic that I can take these numbers as one. If there is any solution for this then please share with some example code.
I don't think you can do this on the database level.
You would have to do something like this:
Create an array of all country codes (including + sign)
Fetch all the numbers from the database
Use array_map() and in the callback run strpos() against each
element in the country code array and if a match is made remove the
country code from the number
Finally after step 4 is finished run the number array through
array_unique()
CODE:
$country_codes = array('+91', '+61');
$numbers_from_db = array('33445322453', '+913232', '3232', '+614343', '024343');
$sanitized_numbers = array_map(function($number) use ($country_codes){
if(substr($number, 0, 1) === "0") {
$number = substr($number, 1);
return $number;
}
foreach($country_codes as $country_code) {
if(strpos($number, $country_code) !== false) {
$number = str_replace($country_code, "", $number);
return $number;
}
}
return $number;
}, $numbers_from_db);
$distinct_sanitized_numbers = array_unique($sanitized_numbers);
Tested and the out put of var_dump($distinct_sanitized_numbers) is:
array(4) {
[0]=>
string(11) "33445322453"
[1]=>
string(4) "3232"
[3]=>
string(4) "4343"
[4]=>
string(5) "24343"
}

undefined index in multidimensional array

I'm using amazon products API.
$ItemAttr = $Item['ItemAttributes'];
Now $ItemAttr contains a multidimensional array.
if(is_array($ItemAttr["Author"])){$Author = implode(", ", $ItemAttr["Author"]);
}else{
$Author = $ItemAttr["Author"];}
Now when i use the above code i'm getting Undefined index: Author in line 1 and line 3
I tried like this
if(isset($ItemAttr["Author"])) {
if(is_array($ItemAttr["Author"])){$Author = implode(", ", $ItemAttr["Author"]);
}else{
$Author = $ItemAttr["Author"];}
}
It eliminates that error.
But later, When I use code like this $RetVal = array( 'Author' => $Author); i'm getting Undefined variable : Author error
Can anyone tell me the proper way?
Please note: $Item['ItemAttributes']; may or may no contain Author key. I mean if the returned product is a book, the array will return author key. Else it will not..
Initialize the empty variable $Author on top?
$Author = ""; //initialize here
if(isset($ItemAttr["Author"]))
{
if(is_array($ItemAttr["Author"]))
{
$Author = implode(", ", $ItemAttr["Author"]);
}
else
{
$Author = $ItemAttr["Author"];
}
}
I implemented the amazon books api just last month and i remember this exact same problem. How lucky are you as i never had me to help :(
Amazon is very annoying because there is no consistency within their returned structure (well, except for what's below, but that makes it annoying to consume):
if one item is returned, it's an OBJECT
if multiple items are returned, it's an ARRAY
if nothing is returned, NOTHING exists at all
Personally i think they should have used empty arrays at least, and stick to arrays. You can always add objects to arrays >< but at least the structure would be consistant.
The way i got around it, was to create a new representation of the returned structure which GUARANTEED that everything was an array and that the WHOLE STRUCTURE was pre-defined. This way i could later access the data knowing 100% that it won't give me errors like it doesn't exist or is being accessed as an object when it is an array.
First, create the structure how you want it to be such as:
$structure = array(
'isbn' => '',
'authors' => array(),
'pictures' => array(),
'title' => ''
);
Then create a function or object method (depending on your style) to consume the amazon data returned and find what it can and insert it into your custom structure.
Remember to check that first it exists, and then if it is an array or an object so you know how to access it. It helps to print out a few returned results from amazon with a few different books.
Then, to access details about the book, you can rely on the data in the $structure ;) everything is an array, and everything is guaranteed to exist so doing:
foreach ($structure['authors']...
Won't produce an error that its not an array, doesn't exist or is in fact an object!!!
The sort of pseudo code would be:
$returned_amazon_data = get_amazon_data('http://amazon.com/api/book=1234567');
$book = consume_amazon_result($returned_amazon_data);
if ($book) {
//print out the authors, if no authors were found, will just stay blank as it's GUARANTEED to always be an array of strings
print implode($book['authors']);
}
Have fun! I know i did(nt)...
You can combine your two conditional statements, as well as predefine $Author:
$Author = '';
if(isset($ItemAttr["Author"]) && is_array($ItemAttr["Author"])){
$Author = implode(", ", $ItemAttr["Author"]);
}elseif(isset($ItemAttr["Author"])){
$Author = $ItemAttr["Author"];
}
this should eliminate both errors.

PHP – Retrieving values from multi-dimensional arrays

I have a working script, but I'm sure that my method of managing arrays could be better. I've searched for a solution and haven't found one, but I'm sure that I should be using the functionality of associative arrays to do things more efficiently.
I have two arrays, one from a CSV file and one from a DB. I've created the CSV array as numeric and the DB array as associative (although I'm aware that the difference is blurry in PHP).
I'm trying to find a record in the DB array where the value in one field matches a value in the CSV array. Both arrays are multi-dimensional.
Within each record in each array there is a reference number. It appears once in the CSV array and may appear in the DB array. If it does, I need to take action.
I'm currently doing this (simplified):
$CSVarray:
('reference01', 'blue', 'small' ),
('reference02', 'red', 'large' ),
('reference03', 'pink', 'medium' )
$Dbarray:
(0 => array(ref=>'reference01',name=>"tom",type=>"mouse"),
(1 => array(ref=>'reference02',name=>"jerry",type=>"cat"),
(2 => array(ref=>'reference03',name=>"butch",type=>"dog"),
foreach ($CSVarray as $CSVrecord) {
foreach ($Dbarray as $DBrecord) {
if ($CSVarray[$numerickey] == $DBrecord['key'] {
do something with the various values in the $DBrecord
}
}
}
This is horrible, as the arrays are each thousands of lines.
I don't just want to know if matching values exist, I want to retrieve data from the matching record, so functions like 'array_search ' don't do what I want and array_walk doesn't seem any better than my current approach.
What I really need is something like this (gibberish code):
foreach ($CSVarray as $CSVrecord) {
WHERE $Dbarray['key']['key'] == $CSVrecord[$numerickey] {
do something with the other values in $Dbarray['key']
}
}
I'm looking for a way to match the values using the keys (either numeric or associative) rather than walking the arrays. Can anyone offer any help please?
use a hash map - take one array and map each key of the record it belongs to, to that record. Then take the second array and simply iterate over it, checking for each record key if the hashmap has anything set for it.
Regarding your example:
foreach ($DBarray as $DBrecord){
$Hash[$record[$key]] = $DBrecord;
}
foreach ($CSVarray as $record){
if (isset($Hash[$record[$CSVkey]])){
$DBrecord = $Hash[$record[$CSVkey]];
//do stuff with $DBrecord and $CSVrecord
}
}
this solution works at O(n) while yours at O(n^2)...
You can use foreach loops like this too:
foreach ($record as $key => $value) {
switch($key)
{
case 'asd':
// do something
break;
default:
// Default
break;
}
}
A switch may be what you are looking for also :)
Load CSV into the db, and use db (not db array) if possible for retrieval. Index the referenceid field.

Categories