I have a small issue. I have a json file which I fetch data from.
When I print_r() the data, I see the field I want. But trying to call them, only 2 on 3 works, one seems to not be fetch-able.
Here the code, if someone have an idea about what's wrong:
Original JSON :
[
{
"ņame": "Xcoin",
"rate": "100.0000",
"status": "online"
}
]
The JSON with print_r()
Array
(
[ņame] => XCoin
[rate] => 100.0000
[status] => online
)
When I fetch individually each fields:
echo $coin['name']."<br>";
echo $coin['rate']."<br>";
echo $coin['status']."<br>";
The result of the previous code:
100.0000
online
Like if the name was not there! How's possible? I have others array and name fetch correctly, using same format.
Look at your array keys: ņ !== n so you're referencing an array index that doesn't exist.
I.e., that is not an n in the JSON you're getting, it's one of these characters.
(TIL this thing is called a cedilla.)
Look it's other character
ņame != name
Related
I run a gaming server and it keeps some information in a database.
I run a MySQL query that pulls information like cargo_items (below).
How can I format this data properly in PHP? I'd like for it to be in a table. Is that possible? My knowledge of handing arrays like this is limited do to the complex nature. This is how the data is returned from the database.
Array
(
[0] => Array
(
[0] => Array
(
[id] => 2237
[cargo_weapons] =>
[
["MMG_02_black_F","","","",[],""],
["arifle_SDAR_F","","","",[],""],
["arifle_SDAR_F","","","",[],""],
["arifle_SPAR_03_khk_F","","","",[],""],
["LMG_Zafir _F","","","",[],""],
["MMG_02_black_F","","","",[],""],
["MMG_02_black_F","","","",[],""]
]
)
)
)
The output should be a table:
Weapons
-------
MMG_02_black_F
arifle_SDAR_F
arifle_SDAR_F
arifle_SPAR_03_khk_F
LMG_Zafir_F
MMG_02_black_F
MMG_02_black_F
Since you have multidimensional array, you need custom recursion function, or, in your specific case, you could use something like this:
function get_items($item, $key)
{
if(!empty($item) && $key=='cargo_weapons')
//your html table cells
echo "$item<br>";
}
array_walk_recursive($array, 'get_items');
array_walk_recursive
will do the job (this function returns true or false), but you can (ab)use it to display desired HTML too.
I have a function using array_search not working ... here is my code
function LangFull($name){
$languageCodes = array(
"abkhazian"=>"ab",
"afar"=>"aa",
"afrikaans"=>"af",
"afrikaans"=>"af-za",
"zulu"=>"zu",
"zulu"=>"zu-za"
);
return ucwords(array_search(strtolower($name),$languageCodes));
}
echo LangFull("zu"); /// Gives no output
echo LangFull("zu-za"); /// Gives output
same with af is no output ... please help
If its possible to interchange, (values to keys and keys to values) and won't have those key collisions, then you can do it that way also:
function LangFull($name){
$languageCodes = array(
"ab" => "abkhazian",
"aa" => "afar",
"af" => "afrikaans",
"af-za" => "afrikaans",
"zu" => "zulu",
"zu-za" => "zulu",
);
return isset($languageCodes[$name]) ? ucwords(strtolower($languageCodes[$name])) : 'Not found';
}
echo LangFull("zu"); /// Gives output
echo LangFull("zu-za"); /// Gives output
echo LangFull("yahoo!");
You have two identical array keys:
"zulu"=>"zu",
"zulu"=>"zu-za"
You need to name one of them something else.
As they are the same, trying to access one of them specifically is futile as PHP does not know which of the two you are requesting.
Alternatively, if you are trying to store more than 1 data value for a given key, you can make the value of a key an array, so can then store more data as required.
e.g.
array (
"afrikaans"=> array(
"af",
"af-za",
),
"zulu"=> array(
"zu",
"zu-za",
)
);
EDIT.
In response to you asking about swapping the keys and values:
You can, and Ghost has shown you how.
However retaining your keys as they are (as my above array example) allows you to collate all relevant data into one index, and can access it easily.
Swapping values and keys will likely make it harder to obtain data you need, as your key is now the "data". So to grab data from an array you'd need to know the data (as it's now the key) and you'd actually be grabbing the reference (what was your key).
Which is a bit odd. It can work, but it's not really ideal.
Using json_decode, I've ended up with an object that looks like this:
$data->foo->bar->1234567->id
I want to access id. There are two problems, both with the number 1234567:
It's an illegal property name.
The number will differ each time, and I can't predict what the number will be. I need a way of accessing id, even when I don't know the number.
I know I can overcome problem (1) with curly braces, but I don't know how to overcome (2). I don't want to use get_object_vars, because the object is likely to be very large, and that function is very slow.
My current solution is simply
foreach ($data->foo->bar as $id); but that feels rather hacky. Is there a better way?
From my comment above, using json_decode(,true) and then resetting.
The example json array looks like:
Array (
[foo] => Array (
[bar] => Array (
[1234567] => Array (
[id] => 1234
)
)
)
)
The code:
<?php
$data = json_decode('{"foo":{"bar":{"1234567":{"id":1234}}}}', true);
reset($data['foo']['bar']);
$number = key($data['foo']['bar']);
echo $data['foo']['bar'][$number]['id'];
Output: 1234
In case you don't need the whole array anymore and only want to get the id you can get it like this:
<?php
$data = json_decode('{"foo":{"bar":{"1234567":{"id":1234}}}}', true);
echo array_shift($data['foo']['bar'])['id'];
Only works if the unknown key is the first element of bar. array_shift removes the element from $data.
I have a PHP function that returns an array. This is the output of print_r($myArray):
Array (
[id] => 8166
[customer_id] => 73
[nickname] => AnnieB
[name] => Anastasia Beaverhausen
[email] => annieb#annieb.com
[phone] => 555-555-5555
[company] => Annie B's
[address1] => 123 Main Street
[address2] => Apartment 555
[city] => Chicago
[state] => IL
[zip] => 55555
[billing] => 1
[residence] => 0
[token] =>
[verified] => 1 )
I should be able to access any of the members by saying something like $myArray['city'], correct? I know I've done this in the past, but it keeps returning an empty string, even when there is a value in the city field.
Any ideas?
==================MORE CODE POSTED PER REQUESTS=============================
I'm using this in Joomla, so there are a few lines that are specific to Joomla. The end purpose of this code is to populate a dropdown list with addresses from a database; the option values contain an imploded string of all column values (to be accessed via javascript later) and the option text is a single field. Here's the code that creates the dropdown:
foreach (getAddresses($AcctID) as $id => $info) {
print_r($info);
$nickName = $info[2];
error_log("nickname=".$nickName);
$infoStr = implode("|", $info);
$addressOptions .= "<option value=\"{$infoStr}\">$nickName</option>";
}
The getAddresses function is here (this is working correctly):
function getAddresses($AcctID) {
$db =& JFactory::getDBO();
$query = "select * from jos_customers_addresses where customer_id = ".$db->quote($AcctID);
$db->setQuery($query);
if (!$db->query()) error_log($db->stderr());
if (!$db->getNumRows())
return false;
else
return $db->loadAssocList();
}
The print_r($info) line is what is returning the array I originally posted. The next two lines are the ones giving me problems:
$nickName = $info[2];
error_log("nickname=".$nickName);
I've also tried $nickName = $info['nickname'] and gotten the same result - no value, even though there's obviously a value in the print_r, and the value does come through correctly in the code generated by the implode line. If you can find someplace between those two lines where I'm overwriting my variable, or whatever, please point it out to me, because I'm clueless as to why I can't get a handle on this value.
I should be able to access any of the
members by saying something like
$myArray['city'], correct?
Yes, that's correct.
I know I've done this in the past, but
it keeps returning an empty string,
even when there is a value in the city
field.
If nothing is showing up, there's probably not a value there, which as the comments said, is most likely a bug in your code (something overwriting that key). To be sure there's nothing there, instead of echo $myArray['city'] try var_dump($myArray['city']) -- this will tell you if it's an empty string (string(0) "") or not set at all (NULL)
Take your print_r($myArray) and put it immediately before the statement where you use $myArray['city']. is the 'city' key still set? If so, double check to make sure you don't have a typo... capitalization matters! If it's not still set, move the print_r($myArray) up a few lines and repeat until you find what's unsetting $myArray['city']
...Or just post more code ;-)
EDIT: Did $info[2] need to be $info['city']?
I am working with a hook_form_alter on a CCK type (for you drupal-ers). I have a field that is normally a select list in my node form. However, in this instance, I want to hide the select list, and populate its value in the form with an SQL query.
Everything was going nicely. I could see that my desired value was showing up in the HTML source, so I knew my query was executing properly. However, when I submit the form, it only inserts the first character of the value. A few of my tests were values of 566, 784, 1004 - the column values were 5,7,1, respectively.
At first I thought it had to be the DB column attributes, but when I removed my form_alter that makes the field hidden and select the value manually, the correct value is inserted?!?
<?php
function addSR_form_service_request_node_form_alter(&$form, $form_state) {
if (arg(0) == 'user' && is_numeric(arg(1))) {
$account = arg(1);
$club = 2589;
$form['field_sr_account'] = array( '#type' => 'hidden',
'#value' => $club
);
}
}
?>
Can anyone see why only the first character would be inserted??
Note: I have tried deleting and recreating the column, using #value & #default_value, and it is still submitting only the first character of the integer. Also, I eliminated the submit handler as a possible cause by removing it, which still resulted in only one character being submitted
More Updates - Still Searching!
Okay, some good questions. Allow me to answer them:
The DB column type is integer(4)
The HTML the hook produces is :
input type="hidden" name="field_sr_account" id="edit-field-sr-account" value="2589"
Latest Update: I think the issue has been narrowed to the structure of the array. When I do var_dump on this field after the form alter has been processed, this is what I get..
[43] => Array
(
[#type] => hidden
[#default_value] => 2589
[#post] => Array
(
)
[#programmed] =>
[#tree] =>
[#parents] => Array
(
[0] => field_sr_account
)
[#array_parents] => Array
(
[0] => field_sr_account
)
[#weight] => 0.016
[#processed] => 1
[#description] =>
[#attributes] => Array
(
)
[#required] =>
[#input] => 1
[#process] => Array
(
[0] => form_expand_ahah
)
[#name] => field_sr_account
[#id] => edit-field-sr-account
[#value] => 2589
[#defaults_loaded] => 1
[#sorted] => 1
)
What is the structure of the field that I can set the form value to. It's gotta be something like what abhaga is suggesting..
Since the field you are trying to change was originally using a select widget, CCK will be looking for $form_state['values']['field_sr_account'][0]['value']. By setting the field to a #hidden type and setting #value, you will get its value in $form_state['values']['field_sr_account']. CCK will try to access the first element of that and end up with the first character of the value.
Updated: The easiest way to achieve what you need would be to do something:
function addSR_form_service_request_node_form_alter(&$form, $form_state) {
if (arg(0) == 'user' && is_numeric(arg(1))) {
$account = arg(1);
$club = 2589;
// Use this property to store the value to restore back
$form['#field_sr_account'] = $club;
$form['field_sr_account'] = array( '#type' => 'hidden','#value' => $club);
}
}
/*in your submit handler, restore the value in the proper format*/
$form_state['values']['field_sr_account'] = array('0' => array('value' => $form['#field_sr_account']));
Old Answer
One way of accomplishing what you are
trying to do is to copy the whole
$form['field_sr_account'] into
$form['#field_sr_account'] and then
provide the value through the SQL
query in the right format in the
submit handler itself.
Ok take a look at http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html#hidden versus http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html#value
It is also recommended you use value instead of hidden. You can find this info on http://api.drupal.org/api/drupal/developer--topics--forms_api.html/6
Also, type hidden is not allowed to have properties your assigning to it so this may be causing a problem. Any usage problems you may be having with the forms API should be answer in those resources as I"m still a little unclear on what you're trying to accomplish... specifically with the submit button.
Old answer:
Ok if I understand this correctly
$club is not being set correctly. If
the first result from your query is
the number your looking for then this
should work.
Try calling
<?php print_r(db_fetch_array($result)) ?>
to get a look at everything returned
from the query.
I'm a little unclear as to what is
being set incorrectly. If it's
#value inside your associated array
then the culprit must be the query.
If #value is being set correctly and
whatever your doing with it later may
be the culprit (not shown here). If
its the values in your $form_state I
don't see that your using $club here
at all.
Also, in your addSR_submit_function
you don't seem to be using the $form
variable, or using $club for anything
except for setting the message which
appears at the top of the page your on
when it's called.
I may need some further clarification
as to what exactly is going wrong.
Also, when you're calling
drupal_set_message function, are you
just doing this for debugging
purposes?
Shouldn't you check
drupal_set_message($form_state['values']['field_sr_account']);
instead of
drupal_set_message($club);
in addSR_submit_function ?
OK, just a quess: not sure what type db_result returns for your query, may be it has something to do with types conversions? So this is to make sure value is int.
'#value' => (int)$club
cinqoTimo, Out of curiosity what kind of CCK field is this? Is it a Integer, Decimal, Float? and do you have any special parameters on that field not normally on by default? What is the column type in the db?
Can you post the html output of the form. That might give a clue as to what might be going on.
Are you using any javascript to edit any values for this field?
Have you tried outputting the value results from addSR_form_service_request_node_submit hook? Any difference there.
Sorry for all the questions. Just thinking out loud as it seems you have covered most of your bases.