I have a form, and the URL is like this:
http://hostname/projectname/classname/methodname/variablename
And in my JavaScript, I fill an array like this:
var currentrelations = new Array();
$(".ioAddRelation").each(function(index) {
currentrelations[index] = $(this).html();
});
And this array has two values ['eeeeee','eeeeee']
So the url is:
http://localhost/Mar7ba/InformationObject/addIO/eeeeee,eeeeee
And in my PHP, in the class InformationObject, on the method addIO:
public function addIO($currentRelations =null) {
$name = $_POST['name'];
$type = $_POST['type'];
$concept = $_POST['concept'];
$contents = $_POST['contents'];
$this->model->addIO($name, $type, $concept, $contents);
if (isset($_POST['otherIOs'])) {
$otherIOs = $_POST['otherIOs'];
$this->model->addOtherIOs($name, $otherIOs);
}
$NumArguments = func_num_args();
if ($currentRelations!=null) {
$IOs = $_POST['concetedIOs'];
$this->model->setIoRelations($name,$IOs, $currentRelations);
}
exit;
include_once 'Successful.php';
$s = new Successful();
$s->index("you add the io good");
}
But when I print the array $currentRelations using this statement:
echo count($currentRelations)
The results was 1 not 2, and when I print the first element using thie statement echo $currentRelations[0] I get e not eeeeee
why is that? What is the solution? What am I doing wrong?
As I commented, the $currentRalations is a string, so using count on any type which is not an array or an object will return 1.
Also, note that when you do this $currentRelations[0] on a string, you are accessing a character in the zero-based index of the string. As strings are arrays of characters you can use the square array brackets to access specific chars within strings. This is why echo $currentRelations[0]; printed e in your code.
To split a string you should use the explode function like this:
$curRel = explode(',', $currentRelations);
and then see what you get
var_dump($curRel);
Hope it helps.
Related
I have a function which receives unlimited number of arguments.
(I am using func_get_args for that)
Example: function generate($one, $two, $three, ...)
Each one of the parameters represents a column in another array (let's call it $array).
I want to receive the value of the another array on $array[$one][$two][$three]
That means that the number of "[]" is unlimited
I have tried to generate a var in var for this.
<?php
$ron = array("sir" => "yes");
$name = 'ron["sir"]';
echo var_dump(${$name});
?>
My result:
Notice: Undefined variable: ron["sir"] in
C:\Users\ronr\Desktop\xampp\htdocs\lol.php on line 5 NULL
If you want to use the args as a path to array value, you can try this:
$result = $array;
$args = func_get_args();
foreach($args as $arg) {
$result = $result[$arg];
}
var_dump($result);
Actually, the error is correct, you are defining a variable named ron["sir"], something like this:
${'ron["sir"]'} = 'foobar';
echo ${'ron["sir"]'};
. To show the value of sir in the $ron array, it should be:
$ron = array("sir" => "yes");
$name = 'ron';
var_dump(${$name}["sir"]);
Currently I am attempting to call a multidimensional array, using a string as a key or keys. I would like to use the following code, but I think the key is being interpreted as a string. Any solution?
$data= [];
$data['volvo'] = "nice whip";
$test = "['volvo']";
$data['drivers']['mike'] = "decent";
$test2 = "['drivers']['mike']";
echo $data$test; // should read 'nice whip'
echo $data$test2; // should read 'decent'
You just use the variable (which should just be the string and not PHP syntax) in place of the string literal.
$cars = [];
$cars['volvo'] = 'nice whip';
$test = 'volvo';
echo $cars[$test];
If you need a dynamic array access solution, you could also write a function, which does the actual array access like this:
function path($array, $path) {
$path = is_array($path) ? $path : explode('.', $path);
$current = $array;
while (count($path)) {
$seg = array_shift($path);
if (!isset($current[$seg])) throw new Exception('Invalid path segment: ' . $seg);
$current = $current[$seg];
}
return $current;
}
In your case, this would look like this
echo path($data, 'volvo');
echo path($data, 'drivers.mike');
or
echo path($data, ['volvo']);
echo path($data, ['drivers', 'mike']);
The problem is you can't pass multiple levels in one string like that. (If so, PHP would have to start looking for code fragments inside string array keys. And how would it know whether to interpret them as fragments and then split the string key up, or keep treating it as one string??)
Alt 1
One solution is to change the structure of $data, and make it a single level array. Then you supply keys for all the levels needed to find your data, joined together as a string. You would of course need to find a separator that works in your case. If the keys are plain strings then something simple like underscore should work just fine. Also, this wouldn't change the structure of your database, just the way data is stored.
function getDbItem($keys) {
// Use this to get the "old version" of the key back. (I.e it's the same data)
$joinedKey = "['".implode("'],['", $keys)."']";
$joinedKey = implode('_', $keys);
return $data[$joinedKey];
}
// Example
$data = [
'volvo' => 'nice whip',
'drivers_mike' => 'decent'
];
var_dump(getDbItem(['drivers', 'mike'])); // string(6) "decent"
Alt 2
Another way is to not change number of levels in $data, but simply traverse it using the keys passed in:
$tgt = $data;
foreach($keys as $key) {
if (array_key_exists($key, $tgt)) {
$tgt = $tgt[$key];
}
else {
// Non existing key. Handle properly.
}
}
// Example
$keys = ['drivers', 'mike'];
// run the above code
var_dump($tgt); // string(6) "decent"
Firstly, look my example json output.
I have next question. I have some fields in json code like 'counter_87' or 'coutner_88' in countersData part. It is a variable. I need to get access to this variable class field.
Ofc, I can write:
foreach($objCounter->countersData as $data)
{
print $data->counter_87;
}
It is working fine. But...
I have counters ID and I need to get access to fields which are named depending on this ID's.
Full code, which will show what I want:
foreach($objCounter->countersData as $data)
{
$row = "<td width=100px>$data->month $data->year</td>";
foreach($objCounter->counters as $counter)
{
$counterId = $counter->id;
$counterValue = "$data->counter_$counterId";
$row .= "<td>$counterValue</td>";
}
$table .= "<tr>$row</tr>";
}
I need same:
$foo = 'bar';
$bar = 'foobar';
echo $$foo; // foobar will be printed
But with classes.
Thank you.
You could also do the following if you don't want to or can't change change your JSON structure as already mentioned in the comments.
$field_name = 'counter_'.$id;
$field_value = $data->$field_name;
$row .= "<td>$field_value</td>";
// or $row .= '<td>'.$data->$field_name.'</td>';
About rewriting the JSON. Here's code that would convert your JSON to the slightly better structure.
$data = json_decode($data_json);
foreach($data->countersData as $counter_data) {
$counters = array();
foreach($counter_data as $key => $val) {
if(substr($key, 0, 8) == 'counter_') {
$counters[substr($key, 8)] = $val;
unset($counter_data->$key);
}
}
$counter_data->counters = $counters;
}
$data_json_new = json_encode($data);
Using an array instead of fields like 'counter_1', 'counter_2' means having structure like this this:
$countersData[0]->counters[90] = 1;
$countersData[0]->counters[89] = 1;
$countersData[0]->counters[88] = 1;
Instead of
$countersData[0]->counters_90 = 1;
$countersData[0]->counters_89 = 1;
$countersData[0]->counters_88 = 1;
This means having an associative array called counters instead of separate fields like 'counter_90' or something. It makes accessing the data programmatically alot easier.
Note that associative array is very similar to the stdClass. Basically a different datatype serving the same purpose. Using an array to represent your data just makes it easier to deal with integer keys. You can use json_decode($data_json, true) to get the data returned as an associative array.
i have a problem i want to add slashes at the starting and the end of each string of my array.
This is an example of my actual array :
$patte = array();
$patte[0] = "httpd";
$patte[1] = "vsftpd";
$patte[2] = 'gohphp';
$patte[3] = 'abcdef';
i use this array for taking information into a DataBase so i can't place slashes now, or this is going to not working.
(mysql_query ... while mysql_fetch_array ...)
I need to rename these entry.
For this i use a second array, and with the command : "preg_replace" i can translate every strings like i want.
But preg_replace want me to add slashes in $patte
I want to obtain an array like this
$pattes = array();
$pattes[0] = "/httpd/";
$pattes[1] = "/vsftpd/";
$pattes[2] = '/gohphp/';
$pattes[3] = '/abcdef/';
Can you help me please.
I'm gonna have like 1000 line into this array.
Using array_map() you can apply callback to every element of your array :
function addSlashes($str)
{
return "/".$str."/";
}
$newArray = array_map("addSlashes", $patte);//array with the new values
Use array_map:
$pattes = array_map(function($str) {
return '/'.$str.'/';
}, $pattes);
I have this code:
function returnArray() {
$intData = array("1", "3");
return $intData[array_rand($intData)];
}
I'm trying to make a function similar to the one above.
Instead of adding integers with commas I'm trying to implode the commas with the integers.
Sort of like a dynamic version of the above using json_decode, file_get_contents, a foreach loop, array, array_rand & return
This is my code:
function Something() {
foreach (json_decode(file_get_contents('removed'), true) as $jsonArr) {
$arrData = array(implode(",", $jsonArr));
$roundData = $arrData[array_rand($arrData)];
return $roundData;
}
}
I was just wondering if I'm doing it right and if the array is correct or not.
Also it doesn't return anything from the array.
When I try to implode, it throws an error
implode invalid argument
It seems you're trying to print a random room_id from the JSON response.
The problem lies here:
$intData = array(implode(",", $arrRoomsReverse['room_id']));
You can't initialize an array like that.
Just push the room_id element to the array, like so:
$intData[] = $arrRoomsReverse['room_id'];
Now, you can simply get a random room_id outside the loop:
$intRoom = $intData[array_rand($intData)];
The function would look like:
function returnArray()
{
$str = file_get_contents('...');
$jsonArr = json_decode($str, true);
foreach ($jsonArr as $arrRoomsReverse)
{
$intData[] = $arrRoomsReverse['room_id'];
}
$intRoom = $intData[array_rand($intData)];
return $intRoom;
}
And to call the function:
echo returnArray();