I am a newbie and have an issue in parsing json.
Below is the json array I want to parse:
array (size=3)
'status' => string 'success' (length=7)
'message' => string '' (length=0)
'data' =>
array (size=2)
0 =>
array (size=2)
'asset' => string 'ONESATOSHI' (length=10)
'balance' => string '0.0000001' (length=9)
1 =>
array (size=2)
'asset' => string 'XCP' (length=3)
'balance' => string '150333.69737005' (length=15)
I want to get the balance of array 1.
I have tried this:
function xcp_balance($wallet)
{
$jarr = json_decode(file_get_contents('http://xcp.blockscan.com/api2.aspx?module=address&action=balance&btc_address='.$wallet),true);
$balance = $jarr['data'][1]['balance'];
if (is_numeric($balance)) {
return $balance;
} else {
return 0;
}
}
$wallet = '1NFeBp9s5aQ1iZ26uWyiK2AYUXHxs7bFmB';
xcp_balance($wallet);
But it not working. Kindly help me and apologies for my language.
Its working. You just forgot to echo the returned value:
function xcp_balance($wallet) {
$jarr = json_decode(file_get_contents('http://xcp.blockscan.com/api2.aspx?module=address&action=balance&btc_address='.$wallet),true);
$balance = $jarr['data'][1]['balance'];
if (is_numeric($balance)) {
return $balance;
} else {
return 0;
}
}
$wallet = '1NFeBp9s5aQ1iZ26uWyiK2AYUXHxs7bFmB';
echo xcp_balance($wallet); // 150333.69737005
// ^ echo it
Working here
And it might be better to check the existence of that index first:
function xcp_balance($wallet) {
$jarr = json_decode(file_get_contents('http://xcp.blockscan.com/api2.aspx?module=address&action=balance&btc_address='.$wallet),true);
$balance = (isset($jarr['data'][1]['balance']) && is_numeric($jarr['data'][1]['balance']) ? $jarr['data'][1]['balance'] : 0);
return $balance;
}
Related
i have this code that saves values from $POST , but one variable [segments] needs to be imploded but i dont know how to achieve that
My code:
$request = $this->getRequest();
if (!$id = $request->id) $this->_redirect('/' . $this->_name);
$guest = ($guestTable = new Table_Guests())->fetchRow(
$guestTable
->select()
->where('id_objects = ?', $this->getObjectId())
->where('id = ?', $id)
);
$this->view->form = $guest->form();
if ($request->isPost() && $this->view->form->isValid($request->getPost())) {
//
implode($_POST['segments']);
$post = $_POST;
unset($post['saveBtn']);
try {
foreach ($post as $key => $value) $guest->$key = $value;
$guest->save();
$this->_helper->flashMessenger(array('info' => $this->view->translate('The changes have been saved')));
} catch (Exception $e) {
$this->_helper->flashMessenger(array('error' => $this->view->translate('Cannot save changes')));
}
$this->_redirect('/' . $this->_name);
}
$this->view->title = $this->view->translate('Guests') . ' <span>/ ' . $this->view->translate('Edit') . '</span>';
Short version of the output :
array (size=27)
'first_name' => string 'Test' (length=4)
'segments' =>
array (size=3)
0 => string 'uno' (length=3)
1 => string 'dos' (length=3)
2 => string 'tres' (length=4)
'birthday' => string '0000-00-00' (length=10)
And one desired thing that needs to be is
'segments'=> string(uno,dos,tres)
Is it possible?
The answer was adding
$_POST['segments'] = implode(',', $_POST['segments'])
I have an array of associative array, I will like to update the values in this array, hence I created a function that looks like this.
//The Array of Associative arrays
array (size=2)
0 =>
array (size=3)
'slang' => string 'Tight' (length=5)
'description' => string 'Means well done' (length=15)
'example-sentence' => string 'Prosper it Tight on that job' (length=28)
1 =>
array (size=3)
'slang' => string 'Sleet' (length=5)
'description' => string 'Means to send on long errand' (length=28)
'example-sentence' => string 'I am going to sleep sia' (length=23)
//The function
public function update($slang, $new)
{
array_map(function($data, $key) use($slang, $new)
{
if($data['slang'] == $slang)
{
$data[$key] = array_replace($data, $new);
}
}, UrbanWord::$data);
}
I tired running this but the original array will not update. I need help on how to go about fixing this please.
Thanks
You may use array_reduce instead of array_map as following:
public function update($array, $slang, $new)
{
return array_reduce($array, function ($result, $item) use ($slang, $new) {
if ($item['slang'] == $slang) {
$item = array_replace($item, $new);
}
$result[] = $item;
return $result;
}, array());
}
Usage:
UrbanWord::$data = $this->update(
UrbanWord::$data,
'Tight',
array('description' => 'another description')
);
var_dump($myUpdatedArray);
If you want to update it directly passing the UrbanWord::$data by reference you may try something like:
class UrbanWord
{
public static $data = array(
array(
'slang' => 'Test',
'Desc' => 'Frist Desc'
),
array(
'slang' => 'Test1',
'Desc' => 'Second Desc'
)
);
}
class MyClass
{
public function update(&$array, $slang, $new)
{
$array = array_reduce($array, function ($result, $item) use ($slang, $new) {
if ($item['slang'] == $slang) {
$item = array_replace($item, $new);
}
$result[] = $item;
return $result;
}, array());
}
}
$myClass = new MyClass();
$myClass->update(UrbanWord::$data, 'Test', array('Desc' => 'test'));
echo '<pre>';
var_dump(UrbanWord::$data);
echo '</pre>';
I have a POST request array that looks like this
$request = array (size=2)
'licence' => string 'uDyQwFwqV7aQG2z' (length=15)
'user' =>
array (size=7)
'first_name' => string 'Danut' (length=5)
'last_name' => string 'Florian' (length=7)
'username' => string 'daniesy9' (length=8)
'password' => string '123456' (length=6)
'rpassword' => string '123456' (length=6)
'email' => string 'daniesy+1#me.com' (length=16)
'phone' => string '9903131' (length=7)
This in fact is an array which represents values sent by a form. I know the name of the elements, for example the username input has the name of user[username] and i have to find the related value from the array, by name. Something like:
$key = "user[username]";
$request[key];
Any idea how to do this?
I know that the correct way to do it is $request["user"]["username"] but it's quite complicated because i have to use the fields names from the form which are user[username], user[firstname], etc and it might have up to 4 levels of depth.
Answered in comments but similar Question to
Convert a String to Variable
eval('$username = $request["user"]["username"];');
Edit
Eval not a valid suggestion as request data.
So I would suggest the second method on this post
<?php
$request = array(
'user' => array(
'username' => 'joe_blogs'
)
);
function extract_data($string) {
global $request;
$found_matches = preg_match_all('/\[\"([a-z]+)\"\]/', $string, $matches);
if (!$found_matches) {
return null;
}
$current_data = $request;
foreach ($matches[1] as $name) {
if (key_exists($name, $current_data)) {
$current_data = $current_data[$name];
} else {
return null;
}
}
return $current_data;
}
$username = extract_data('request["user"]["username"]');
?>
function findInDepth($keys, $array){
$key = array_shift($keys);
if(!isset($array[$key])){
return FALSE;
}
if(is_array($array[$key])){
return findInDepth($keys, $array[$key]);
}
return $array[$key];
}
$key = "user[username]";
$keys = preg_split("/(\[|\])/", $key);
echo findInDepth($keys, $request);
This function solves my problem. It first splits the string (aka the input name) into an array of keys and then recessively searches in depth the array by keys until it finds a value which is not an array and returns FALSE otherwise.
You could separate keys with dots. Primitive example:
<?php
class ArrayDot
{
protected $array = [];
public function __construct(array $array) {$this->array = $array;}
public function get($path)
{
$array = $this->array;
foreach(explode('.', $path) as $key) {
$array = $array[$key];
}
return $array;
}
}
$array = [
'user' => [
'username' => 'tootski',
]
];
$a = new ArrayDot($array);
echo $a->get('user.username'); # tootski
I'm using urlencode & urldecode to pass variables trough a html-form.
$info = 'tempId='.$rows['tempID'].'&tempType='.$rows['tempType'].'&dbId='.$rows['ID'];
echo '<input type="hidden" name="rank[]" value="'.urlencode($info).'" >';
Here is what is in $rows
array (size=4)
'ID' => string '110' (length=3)
'tempID' => string '1' (length=1)
'tempType' => string 'temp_first' (length=10)
'pageOrder' => string '0' (length=1)
So $info is
tempId=1&tempType=temp_first&dbId=110
But if i then decode it, it losses 1 parameter. How is this possible?
foreach (explode('&', urldecode($list[$i])) as $chunk) {
$param = explode("=", $chunk);
$tempId = urldecode($param[0]); // template id
$tempType = urldecode($param[1]); // Template type
$dbId = urldecode($param[2]); // database ID
var_dump($param);
}
Output:
array (size=2)
0 => string 'dbId' (length=4)
1 => string '110' (length=3)
Sometime there are even things in the array wich should not be in there, for example instead of temp_first it says tempType. Just the variable name.
I hope you guys can help me
There's no need to explode and process the string manually, you can use parse_str():
parse_str(urldecode($list[$i]), $output);
var_dump($output);
Would output:
array
'tempId' => string '1' (length=1)
'tempType' => string 'temp_first' (length=10)
'dbId' => string '110' (length=3)
try this
$result=array();
foreach (explode('&', urldecode($list[$i])) as $chunk) {
$param = explode("=", $chunk);
$result[$param[0]]=$param[1];
}
var_dump($result);
Could you try this and check the result (I'm groping in the dark though):
//change this <input type="hidden" name="rank[]" value="'.urlencode($info).'" > to
//<input type="hidden" name="urlargs" value="'.urlencode($info).'" >
$values = explode('&',urldecode($_POST['urlargs']));
$arguments = array();
foreach($values as $argument_set){
$data = explode('=',$argument_set);
$arguments[$data[0]] = $data[1];
}
var_dump($arguments);
I believe the problem is in the way you're processing the value
$data=array();
foreach (explode('&', urldecode($list[$i])) as $chunk) {
$param = explode("=", $chunk); //
$data[$param[0]]=$param[1]
}
Instead of grouping all code together, start by putting it in seperate vars and echo the content for debugging. Because you are saying you loose one variable, but the output you show is just one of the variables. What is the var_dump of the other two?
Because your var_dump($param); would output the part before the '=' and after the '=', so indeed i would expect the output to be something like: So which one of these are you missing?
array (size=2)
0 => string 'tempId' (length=6)
1 => string '1' (length=1)
array (size=2)
0 => string 'tempType' (length=8)
1 => string 'temp_first' (length=10)
array (size=2)
0 => string 'dbId' (length=4)
1 => string '110' (length=3)
DEBUG code:
foreach ($list as $row) {
echo 'Full row:: '. $row.'<br>';
//if the data is comming via GET or POST, its already decoded and no need to do it again
$split = explode('&', urldecode($row));
foreach($split as $chunk) {
echo 'Chunk:: '.$chunk.'<br>';
$param = explode('=', $chunk);
echo 'param name:: '.$param[0].'<br>';
echo 'param value:: '.$param[1].'<br>';
}
}
Here is a var_dump or an array returned from my MODEL:
array (size=5)
0 =>
array (size=3)
0 =>
object(stdClass)[19]
public 'X_SIZE' => string '1.75x3' (length=6)
1 =>
object(stdClass)[20]
public 'X_SIZE' => string '1.75x3.5(slim)' (length=14)
2 =>
object(stdClass)[21]
public 'X_SIZE' => string '2x3' (length=3)
1 =>
array (size=3)
0 =>
object(stdClass)[17]
public 'X_PAPER' => string '14ptGlossCoatedCoverwithUV(C2S)' (length=31)
1 =>
object(stdClass)[18]
public 'X_PAPER' => string '14ptPremiumUncoatedCover' (length=24)
2 =>
object(stdClass)[24]
public 'X_PAPER' => string '16ptDullCoverwithMatteFinish' (length=28)
2 =>
array (size=2)
0 =>
object(stdClass)[23]
public 'X_COLOR' => string '1000' (length=4)
1 =>
object(stdClass)[22]
public 'X_COLOR' => string '1002' (length=4)
3 =>
array (size=4)
0 =>
object(stdClass)[26]
public 'X_QTY' => string '100' (length=3)
1 =>
object(stdClass)[25]
public 'X_QTY' => string '250' (length=3)
2 =>
object(stdClass)[29]
public 'X_QTY' => string '500' (length=3)
3 =>
object(stdClass)[30]
public 'X_QTY' => string '1000' (length=4)
4 =>
array (size=3)
0 =>
object(stdClass)[28]
public 'O_RC' => string 'YES' (length=3)
1 =>
object(stdClass)[27]
public 'O_RC' => string 'NO' (length=2)
2 =>
object(stdClass)[33]
public 'O_RC' => string 'NA' (length=2)
My controller is sending to my view and on my view the above dump is of: var_dump($printerOptions)
Ok so I need to create a dropdown menu for each of these arrays and radio buttons for the O_RC array.
I am using codeigniter and using form_dropdown('',$val); inside of a foreach loop causes multiple dropdowns for each key and element in the array.
foreach ($printerOptions as $Options)
{
//var_dump($Options);
foreach ($Options as $Specs)
{
echo $Specs->X_SIZE;
echo $Specs->X_PAPER;
echo $Specs->X_COLOR;
echo $Specs->X_QTY;
echo $Specs->O_RC;
}
}
This ^ code will echo out the expected values of the corresponding arrays but for some reason I get LOOPING errors with the output:
Undefined property: stdClass::$X_PAPER
Undefined property: stdClass::$X_COLOR
Undefined property: stdClass::$X_QTY
Undefined property: stdClass::$O_RC
Looking at my array how can I create a dropdown menu for each of the arrays respectively?
Thanks for the help.
MODEL /// Update ///
class M_Pricing extends CI_Model {
function get_prices()
{
$table_by_product = 'printer_businesscards'; //replace with URI Segment
//Get all the columns in the table set by the page URI of $table_by_product variable
$get_all_col_names = $this->db->list_fields($table_by_product);
//Loop through the column names. All names starting with 'O_' are optional fields for the
//current product. Get all Distinct values and create a radio button list in form.
$resultArray = array();
foreach ($get_all_col_names as $key => $value) {
//get all o_types for the product by column name
if (preg_match('/O_/', $value))
{
$v = (array('Specs' => $value));
foreach ($v as $vals) {
$this->db->select($vals);
$this->db->distinct();
$qX = $this->db->get($table_by_product);
$resultArray[] = $qX->result();
}
}
//Get all x_types for the product by column name. All 'X_' types are specific product options.
//Create a dropdown menu with all DISTINCT product options.
if (preg_match('/X_/', $value))
{
$v = (array('Type' => $value));
foreach ($v as $vals) {
$this->db->select($vals);
$this->db->distinct();
$qX = $this->db->get($table_by_product);
$resultArray[] = $qX->result();
}
}
}
//return $resultArray
//var_dump($resultArray); die;
return $resultArray;
}
As i understand your result array should be object or hash and look like:
array('Type'=>array(
'X_SIZE'=>array('1.75x3','1.75x3.5(slim)','2x3'),
'X_PAPER'=>array('14ptGlossCoatedCoverwithUV(C2S)','14ptPremiumUncoatedCover'),
///...),
'Specs'=>array(
//...)
);
to loop through such structure:
//Types
echo 'Types';
foreach ($Options['Types'] as $type=>$values) {
echo $type;
echo "<select>";
foreach ($values as $value) {
echo "<option value="$value">$value</option>";
}
echo "</select>";
}
//Specs
echo 'Specs';
foreach ($Options['Specs'] as $type=>$values) {
echo $type;
echo "<select>";
foreach ($values as $value) {
echo "<option value="$value">$value</option>";
}
echo "</select>";
}
model:
<?php
class M_Pricing extends CI_Model {
function get_prices()
{
$table_by_product = 'printer_businesscards'; //replace with URI Segment
//Get all the columns in the table set by the page URI of $table_by_product variable
$get_all_col_names = $this->db->list_fields($table_by_product);
//Loop through the column names. All names starting with 'O_' are optional fields for the
//current product. Get all Distinct values and create a radio button list in form.
$resultArray=array();
$resultArray['Options']=array();
$resultArray['Specs']=array();
foreach ($get_all_col_names as $key => $value) {
//get all o_types for the product by column name
$opt_type="";
if (preg_match('/O_/', $value)) {$opt_type="Options";} elseif
(preg_match('/X_/', $value)) {$opt_type="Specs";} else {continue;}
if (!isset($resultArray[$opt_type][$value])) {$resultArray[$opt_type][$value]=array();}
$this->db->select($value);
$this->db->distinct();
$qX = $this->db->get($table_by_product);
foreach ($qX->result() as $v) {
$resultArray[$opt_type][$value][]=$v->$value;
}
}
//return $resultArray
//var_dump($resultArray); die;
return $resultArray;
}
}