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'])
Related
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>';
Question:
I have an array of post values that looks like:
$_POST['children'] = array(
[0]=>array(
'fname' => 'name',
'mname' => 'mname',
'lname' => 'lname,
'dob' => '10/17/1992
),
[1]=>array(
'fname' => 'name',
'mname' => 'mname',
'lname' => 'lname,
'dob' => '10/17/1992
),
[2]=>array(
'fname' => 'name',
'mname' => 'mname',
'lname' => 'lname,
'dob' => '10/17/1992
)
);
// and so on
I have a script set up in my my view functions that checks for old input, and repopulates the values in the case that the form does not validate. I need to find a way to return the above array as a series of key/value pairs i.e.
'children[0][fname]' = 'name'
'children[0][mname]' = 'mname'
'children[0][lname]' = 'lname'
// ... and so on for all fields
Ideally, I would like this to work with an array of any depth, which makes me think I need some sort of recursive function to format the keys. I am having a terrible time getting my head around how to do this.
What I have tried
I have been working with the following function:
function flatten($post_data, $prefix = '') {
$result = array();
foreach($post_data as $key => $value) {
if(is_array($value)) {
if($prefix == ''){
$result = $result + flatten($value, $prefix. $key );
}else{
$result = $result + flatten($value, $prefix. '[' . $key . ']');
}
}
else {
$result[$prefix . $key .''] = $value;
}
}
return $result;
}
This gets me somewhat close, but isn't quite right. It returns the following when I feed it my $_POST array
[children[1]fname] => test
[children[1]mname] => test
[children[1]lname] => test
[children[1]dob] =>
// Expecting: children[1][fname] => test
// ...
Or is there potentially an easier way to accomplish this?
What ended up working for me:
function flatten($post_data, $prefix = '') {
$result = array();
foreach($post_data as $key => $value) {
if(is_array($value)) {
if($prefix == ''){
$result = $result + flatten($value, $prefix. $key );
}else{
$result = $result + flatten($value, $prefix. '[' . $key . ']');
}
}
else {
if( $prefix == ''){
$result[$prefix . $key.''] = $value;
}else{
$result[$prefix . '['.$key.']'.''] = $value;
}
}
}
return $result;
}
it wasn't accounting for the return value of the last call of the recursive function being a scalar value. The addition of these this if/else statement seems to have resolved it.
if( $prefix == ''){
$result[$prefix . $key.''] = $value;
}else{
$result[$prefix . '['.$key.']'.''] = $value;
}
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;
}
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
array_push($info["First_Names"], "$fname");
array_push($info["Last_Names"], "$lname");
array_push($info["Gender"], "$gender");
Does anyone see an issue? Array push is just replacing variables instead of adding them. The variables of $fname, $lname, and $gender are defined by the user in a form. I want the variables to simply be added to the end of the array instead of being replaced. Any responses are appreciated.
if $info["First_Names"] ,$info["Last_Names"] ,$info["Gender"] are arrays ,I don't see any problem .
$info = array();
$info["First_Names"] = array();
$info["Last_Names"] = array();
$info["Gender"] = array();
$fname = 'Fname1';
$lname = 'Lname1';
$gender = 'M';
array_push( $info["First_Names"] ,$fname );
array_push( $info["Last_Names"] ,$lname );
array_push( $info["Gender"] ,$gender );
$fname = 'Fname2';
$lname = 'Lname2';
$gender = 'F';
array_push( $info["First_Names"] ,$fname );
array_push( $info["Last_Names"] ,$lname );
array_push( $info["Gender"] ,$gender );
var_dump( $info );
Outputs :
array (size=3)
'First_Names' =>
array (size=2)
0 => string 'Fname1' (length=6)
1 => string 'Fname2' (length=6)
'Last_Names' =>
array (size=2)
0 => string 'Lname1' (length=6)
1 => string 'Lname2' (length=6)
'Gender' =>
array (size=2)
0 => string 'M' (length=1)
1 => string 'F' (length=1)
From the manual:
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
e.g.
<?php
$info["First_Names"][] = $fname;
$info["Last_Names"][] = $lname;
$info["Gender"][] = $gender;
?>
Alternative is use a function.
<?php
function add_in_key_array($array, $key, $value){
$array[$key][] = $value;
}
?>