I want to call the function from an array .My code is
$params = array(
'df' => $this->_data['df'],
'fl' => implode(',', $this->_data['fl']),
'wt' => $this->_data['wt'],
'q' => $this->_data['select'],
'sort' => '',
'fq' => implode(' ', $fq),
'indent' => 'true',
'start' => $this->_data['range'][0],
'rows' => $this->_data['range'][1],
'defType' => $this->_data['defType'],
'qf' => implode(' ', $qf),
);
i want to call function-"WordSplit" from an array:
'q' => WordSplit($this->_data['select']);
Is it possible to do this in PHP?
Thanks in Advance!!!
As has been said, "the answer is, 'yes.'" WordSplit() is a function, therefore a call to that function is a valid expression. It can be used to provide a value for an array-element.
Now, what I would do, instead, is to add a new statement after the existing one:
$params['q'] = WordSplit(params['q']);
Why? Because the very-harried person who's reading our code, someday in the future, might not notice that element 'q' is being handled differently! Purely for the sake of readability (and possible future maintainability), I would choose to do this as a separate statement. The $params array is first "assembled," in a construct where the action for every element in the array is more-or-less the same. Then, element 'q' is manipulated. (And I would place all other such "manipulations" adjacent to this one. "Clarity... Clarity...")
Related
For a client, I'm building a link between the client's application and a third party's application. The third party's application expects fields like below:
<General>
<Signing>
<Signing>
<FieldA></FieldA>
<FieldB></FieldB>
<FieldC></FieldC>
</Signing>
<Signing>
<FieldA></FieldA>
<FieldB></FieldB>
<FieldC></FieldC>
</Signing>
</Signing>
</General>
We're building the input for the link in PHP, by means of a multi-dimensional associative array. So the above XML would compute to the following PHP:
'General' => array(
'Signing' => array(
'Signing' => array(
'FieldA' => '',
'FieldB' => '',
'FieldC' => ''
),
'Signing' => array(
'FieldA' => '',
'FieldB' => '',
'FieldC' => ''
)
)
)
There's a few problems.
There's no such thing as duplicate keys in an associative array. The output would be messed up.
The third party NEEDS it like this, this is just how they set up their application.
Even if there was such a thing as duplicate kets in an associative array, there is no way that would outputto what the third party expects. The Signing would just be overwritten with the last Signing item.
My question is, how do I make a dynamic associative array (so the number of Signings can vary) with duplicate Signing keys that still outputs every instance of Signing, instead of just one Signingfield with just the last instance.
I hope this makes sense. I'm foreign and my brain is chaos so I'm terrible at explaining things.
Thanks in advance!
You cannot express the same data structure literally in PHP, period. You'll have to express it differently and your XML-serialiser will have to translate appropriately between the PHP array structure and the expected XML representation. A sensible PHP array structure would be this:
'General' => array(
'Signing' => array(
array('FieldA' => '', 'FieldB' => '', 'FieldC' => ''),
array('FieldA' => '', 'FieldB' => '', 'FieldC' => ''),
)
)
The XML serialiser would do something akin to:
foreach ($array['General']['Signing'] as $signing) {
$xml->General->Signing->appendChild('Signing')
..
}
How exactly to do this depends on your XML serialisation process. Suffice it to say that the data structure doesn't need to be/can't be literally identical and will require a translation layer.
I have something like this:
array('fields' => array(
0 => array('name' => 'family_name',
'label' => 'Family Names'),
array('name' => given_names',
'label' => 'Given Names'),
array('name' => 'additional_names',
'label' => 'Additional Names'),
array('name' => 'honorific_prefixes',
'label' => 'Honorific Prefixes'),
array('name' => honorific_suffixes',
'label' => 'Honorific Suffixes')
)
)
in a variable as string. The whole thing is in one database field. If I output the variable, it is a string.
I would have an array with the content as subarrays. How do I convert this value into an array?
I searched with google, but I found explode and split and so on, but I think I miss the key word to find any solution.
Thank you for any help in this case.
Try using eval(), https://secure.php.net/manual/en/function.eval.php
eval("\$array = $string;");
print_r($array);
Your string is not built correctly to put it into the eval function. Two strings inside don't have the preceding quote and that will lead to a parse error. But you can correct it with:
$string = str_replace("=> given_names'", "=> 'given_names'", $string);
$string = str_replace("=> honorific_suffixes'", "=> 'honorific_suffixes'", $string);
After that you can use the answer of shapeshifter (please mark his answer as the correct one):
eval("\$array = $string;");
var_dump($array);
If you just look for a method to save and restore your arrays you could also use serialize / unserialize.
This is driving me mad.. I have a PHP script that returns an array in the form $key => $value and I want to rename the key so that I can display it in a table header. I saw there are several ways of doing this but I'm not sure they are what I need... Either that or I haven't understood the examples correctly which is the likely problem.
Basically my array keys differ each time I iterate over a foreach loop and also some can be blank. How can I get round this?
The first output might look like this:
'_can_chaccess' => false,
'_can_chown' => false,
'_can_delete' => false,
'_can_modify' => false,
'_can_read' => true,
'assigned_to_name_879' => 'Unassigned',
'id' => 1,
'type' => 'Private::Reporting::DataViewModel::DataView_223_42858',
'type_877' => 'Email',
The next run through, I might get this:
'_can_chaccess' => false,
'_can_chown' => false,
'_can_delete' => false,
'_can_modify' => false,
'_can_read' => true,
'assigned_to_name_793' => 'Consultants',
'id' => 1,
'object_reference_794' => 'CASE-1004',
'summary_795' => 'Deployment of New System for HQ (Project)',
'type' => 'Private::Reporting::DataViewModel::DataView_200_42858',
),
As you can see, some keys rename the same e.g. id, type. But the most important ones that I am interested in change each time e.g. Assigned To Name.
Any ideas?
Where do you receive your data from?
You can either somehow modify the source of your data, so if it were a query (what I do not assume here), you have the SELECT ... AS ... statement.
First you do need to know how to interpret the changing keys. If e.g. "assigned_to_name_879" and "assigned_to_name_793" is the same field, you can define a canonical function, which mapps both inputs to a unique output.
The output of the cannonical function and as well the other array keys can serve as keys for an additional array, which contains the table headers of your output.
So your current array is the value's array, and by hand you define a header's array:
array(
'assigned_to_name_879' => 'Name assignment'
);
This dynamic way of storing the table headers in an array only makes sense if you are using the array twice. Otherwise you could simply write the header in the html-code which you do output.
I've managed to figure it out using the below:
$mappings_array = array();
foreach ($report['data'][0] as $key => $value) {
$workbooks->log('Old Key', $key);
preg_match_all('([^_\d]+)', $key, $new_key);
$workbooks->log('New Key', $new_key);
$str = implode(" ", $new_key[0]);
$capitalised = ucwords($str);
array_push($mappings_array,$capitalised);
}
Maybe it's not the best solution but it works :) I get the following output:
> New array: «array (
0 => 'Can Chaccess',
1 => 'Can Chown',
2 => 'Can Delete',
3 => 'Can Modify',
4 => 'Can Read',
5 => 'Id',
6 => 'Total Type',
7 => 'Type',
8 => 'Type',
)
Im looking to use a PHP array obtained from a RESTful service.
They array is just a simple array outputted as follows,
array (
0 =>
stdClass::__set_state(array(
'id' => '375',
'primary_name' => 'Beaufort 3',
'price' => '',
'sqft' => '2435',
'bdrm' => '3',
'bthm' => '2.5',
'display_title' => 'Traditional A1',
'full_img_path' => '',
'thumb_path' => '',
'available_in' => 'a:2:{i:0;s:1:"2";i:1;s:1:"5";}',
'display_first' => '',
)),
)
I'm obtaining the data using file_get_contents but of course its no longer an array at this point. What is the best way to convert this back to a usable array?
I have never seen a service that provides this, probably because it is something people would avoid using, but it does look like it could be something they intend for you to be able to use with eval(). I suppose this could be intended as a convenience. I think they have made an error, though. If you use var_export, (which I assume is how this was generated) on an array like this:
$example = array (
array(
'id' => '375',
'primary_name' => 'Beaufort 3',
'price' => '',
'sqft' => '2435',
'bdrm' => '3',
'bthm' => '2.5',
'display_title' => 'Traditional A1',
'full_img_path' => '',
'thumb_path' => '',
'available_in' => 'a:2:{i:0;s:1:"2";i:1;s:1:"5";}',
'display_first' => '',
)
);
then you would get something you could eval into a variable and use in your code. However, if you var_export an array of anonymous objects instead of an array of associative arrays, you will get the type of response you are getting, which I don't know of any way to use. I would guess they are var_exporting the results of a query and they are using FETCH_OBJ instead of FETCH_ASSOC for the fetch style.
EDIT:
I was looking through the comments on var_export after writing this and came across this way of doing it that should work.
$str = str_replace("stdClass::__set_state", "(object)", $str);
eval('$array=' . $str . ';');
But just because something is possible doesn't mean we should do it.
You can convert it back into an array with eval(). http://php.net/manual/en/function.eval.php
eval('$array='.$response.';');
However, this can be dangerous, because eval will take any PHP code given it - if the service is compromised, your code would execute anything passed to it. JSON, if the service supports it, is much safer and natively supported in PHP since 5.2 via json_decode(). http://php.net/manual/en/function.json-decode.php
Let's say I have an array
$array = array(
'username' => "username",
'location' => "location",
'other' => "other");
This array can hold data for many users, so there could be different values for each 'username', 'location', and 'other' fields. How can I use in_array() or another function to determine if a specific username exists in the array already? Because what if a user has a username like "nyc" and a location of "nyc" and I do
in_array("nyc", $array);
How exactly should something like this be approached?
Thank you.
To achieve something that I think is what you want, you can make an array of associative arrays that have the same keys.
<?php
// This syntax will work only on PHP 5.4
$a=[["name"=>"john","age"=>25],["name"=>"philip","age"=>110]];
print_r(array_filter($a, function($item) {return $item["name"] === "john"; }));
?>
Outputs:
Array
(
[0] => Array
(
[name] => john
[age] => 25
)
)
If you just wanted to know if a person named John was in the list, you can just use sizeof/count on the returned array.
This will allow you to have any number of duplicates, and you don't need to specify any keys. Check out the functions: array_filter, array_reduce, array_map. With all of these, you can process your list using closures like in my example above.
Instead of using associative arrays in your array, you could have objects too. Objects are more heavyweight, and need initialization and stuff, so it is grotesque for using them for tiny static (hardcoded) lists. But they may come handy when your data structures grow and you want to make sure every list item has a certain property (the constructor of the class could ensure that everything is initialized). But the good thing is that filter, reduce and map would still work. The "$item" would then be your object.
$users = array( 'user_id' => array('username' => "username",
'location' => "location",
'other' => "other");
user_id is their NUMBER user_id
So you then call $users['####']['username'];
IE:
$users = array( '1' => array('username' => 'Jim',
'location' => 'Florida',
'other' => "other"),
'2' => array('username' => 'Jane',
'location' => 'Maryland',
'other' => "Grapes"));
Then use array_keys() to search for their user_id