I have an array like so:
$json = array('error'=>true);
But I'd like to perhaps add more keys and values to this at a later time. My feeble knowledge tried this:
$json .= array('something'=>'else');
Which doesn't work. I found array_push but it seems this is for just pushing in new values - not keys. How is this achieved so that with 2 separate declarations I end up with the equivalent of:
$json .= array('error'=>true,'something'=>'else');
there are many ways to accomplish this:
$json['keyname'] = 'something
$json[] = 'something' <- numerical incremented key
array_push($json, 'value') <- same as above
$json = array_merge($json, $some_other_array) <- mixes the two arrays together
Just keep in mind that arrays are not strings
Related
I am trying to convert this JSON string into a PHP array. The JSON string is stored in my database and I have already retrieved it.
{
"users": "user1, user2"
}
I need to convert the above JSON string into an array like the following but dynamically.
$myArray = array("user1", "user2")
This is my code:
$row = mysqli_fetch_array($result);
$json = $row['json'];
$decode = json_decode($json);
$list = $decode->users;
$myArray = explode(',', $list);
This code doesn't work in my program but when I print the array with print_r it looks identical to if I print $myArray from the nondynamic string. This is a concern because the nondynamic string works.
The separator between the usernames is comma+space, you're just using comma when you explode, so the second and following usernames are getting a space at the beginning. Try:
$myArray = explode(', ', $list);
I recommend that you change the JSON structure so you store an actual array, rather than a comma-separated list.
{
"users": ["user1", "user2"]
}
Even better would be to change your database structure so the users are in a real table, rather than being wrapped in JSON. This would allow you to perform queries that search for users easily and efficiently.
I have an array of objects that are defined as {'preference name',value}. For example
$preferences[] = {'abc',123};
$preferences[] = {'def',456};
I'd like to access them like this:
$pref = $preferences['abc'];
Of course, I know I could assign them as a keyed array to begin with, however I'm getting the values via JSON, and json_decode always creates an array of objects. Some example JSON that leads us to the situation above would be:
{'abc':123,'def':456}
Obviously it's trivial to covert these using a loop, but I wondered if there was a better one-liner that might do the job?
If you decode the JSON into associative arrays AND all properties are unique, then just merge the sub arrays:
$preferences = json_decode($json, true);
$preferences = call_user_func_array('array_merge', $preferences);
Seems ugly, but hey, it works.
<?php
$a = ['abc'=>123,'def'=>456];
$obj = json_decode(json_encode($a));
var_dump($obj->abc); //123
$arr = (array)$obj;
var_dump($arr["abc"]); //123
$myArray = array();
for($i=0;i<2;$i++){
..
.. //get the content logic here
assign it to array
$myArray["item"]["content"] = $item_content;
}
echo json_encode($myArray);
The above code produced this result:
Which has an error because I didn't merge them.
I tried to merge like this:
$finalJson = array_merge($finalJson, $myArray);
but the output of echo $finalJson is one object instead of 3.
Update:
Your real problem is down to your use of array_merge on an associative array. The behaviour of array_merge is to reassign duplicate keys if they are associative (cf the docs):
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
And because $myArray is clearly using strings as keys, the values in $finalJson are being reassigned. What you need to do is either create unique keys on each iteration, or simply push the values of $myArray onto a numerically indexed $finalJson array (like I showed in my original answer below)
The problem is simply this:
$myArray["item"]["content"] = $item_content;
it's inside the loop, each time reassigning the value of $myArray["item"]["content"], and not adding it to the array. I suspect that what you wanted to do is add this at the bottom of your loop (for each new value of $myArray):
$finalJson[] = $myArray;
Then, on the next iteration, $myArray will be reassigned, and its new value will be appended to the $finalJson variable.
i have a tricky problem.
What i do.
I generate from the System Tables of Databases (DEV ,Test Prod setup) information for Tables, Vies trigger … with PHP and compare the results ti see teh differences with JavaScript.
Also I have a Documentation DB for additional business information which was installed only once on TEST DB.
Therfore I need to connect all four environments to get the data.
I use
if ($flag === 'i')
for information DB and
elseif ($flag === 's')
for system db‘s.
Result is $row_array and $info_array which must be combined and sendet back to Javascript.
$json_response = array_merge($rinfo, $rsql );
echo json_encode($json_response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
I try this merge in a different positions in the program.
First time in
elseif ($flag === 'i') {
result json:
[
{
"0": "ACT",……….
} ][ ]
second time after } //ifelse return also 2 arrays
[{"0":"ACT","1":"Tabelle Akten","2":"hh","3":null,"4":null,"5":"UCC","6":"Y","7":"Reload Data in Test","8":"y","9":"delete all older tha","10":"n","11":" ","12":"y","13":" ","14":"o","15":"y","16":"o","17":"y","18":"y","19":"Diese tabelle speichert die Acten Verweise","20":"Gert Dorn","21":1570254359,"TDESCRIPTION":"n","TTYPE":" ","TREC_ESTIM":"y","TREC_GROWTH":" ","TDOMAIN":"o","TREL_TYPE":"y","TREL_RULES":"o","THOUSEKEEPING":"y","THOUSE_RULES":"y","TCID":"Diese tabelle speichert die Acten Verweise","TCID_RULES":"Gert Dorn","TUSE_UCC":1570254359,"TUSE_DWH":"","TUSE_ODS":"","TUSE_CWF":"","TUSE_IWF":"","TUSE_OWF":"","TUSE_DEP_MANAGER":"","TENTITY_DESCRIPTION":"","TOWNER":""
,"TTIMESTAMP":""**}][{**"0":"ACT","1":"DB2INST1"
,"2":"USERSPACE1","3":null,"4":"2018-11-21 16:43:20.066567","5":"2018-12-07 10:12:10.255759","6":null,"7":"2020-03-26","8":"2018-11-21 16:43:20.343258","9":3,"NAME":"ACT","CREATOR":"DB2INST1","TBSPACE":"USERSPACE1","REMARKS":"","CTIME":"2018-11-21 16:43:20.066567","STATS_TIME":"2018-12-07 10:12:10.255759","STATISTICS_PROFILE":"","LASTUSED":"2020-03-26","ALTER_TIME":"2018-11-21 16:43:20.343258","COLCOUNT":3}]
The program code and result you can download at
http://dmdg.io/dmdg.zip
Hope you can help Kind regards gert
Did you consider using array_push?
array_push is always preferred than myArray[] = $value
Consider I have associative array with same key values:
$arr = {'MessageID' =>1 ,'MessageID' =>5 , 'MessageID' => 8};
Now I want every call to function foo() which will insert a new key value of 'MessageID'=>integer
How can we do that without overriding other existing key values pairs?
As many answerers before, you can't have keys with the same string in the array in PHP. If you want to represent multiple values per key I use something like this:
$arr = ['MessageID' => [1, 5, 8]];
You would append to MessageID with this code:
$arr['MessageId'][] = 10;
Then it would look like this:
['MessageID' => [1, 5, 8, 10]]
This worked well for me with HTTP headers and other things which are key value based, but can have multiple values.
In php array, you can not insert multiple values with same index.
If you want to use it then you can use it with following manner
$MessageID = array(1,5,8);
and
$MessageID[] = $newValue; to insert new value.
You cannot have an array with duplicate keys.
A better implementation would be to have an array called $messageIDs and save the actual values in the array:
$messageIDs = array (1, 5, 8);
As i mentioned in comments, you cannot have duplicate keys in an array. Also your sample with curly braces is not valid php syntax.
Perhaps you need a multidimentional array:
$arr = [['messageID'=>1],['messageID'=>5],['messageID'=>8]];
in which case you would add another value like so:
$arr[] = ['messageID'=>11];
Is it possible in php to change the name used to create an associative array? I am using mongo in php but it's getting confusing using array() in both cases of indexed arrays and associative arrays. I know you can do it in javascript by stealing the Array.prototype methods but can it be done in php my extending the native object? it would be much easier if it was array() and assoc() they would both create the same thing though.
EDIT -------
following Tristan's lead, I made this simple function to easily
write in json in php. It will even take on variable from within
your php as the whole thing is enclosed in quotes.
$one = 'newOne';
$json = "{
'$one': 1,
'two': 2
}";
// doesn't work as json_decode expects quotes.
print_r(json_decode($json));
// this does work as it replaces all the single quotes before
// using json decode.
print_r(jsonToArray($json));
function jsonToArray($str){
return json_decode(preg_replace('/\'/', '"', $str), true);
}
In PHP there is no "name used to create an associative array" or "name used to create an indexed array". PHP Arrays are ordered maps like in many other scripting languages.
This means that you can use an array whichever way you please.
If you wanted an indexed array..
$indexedArray = array();
$indexedArray[] = 4; // Append a value to the array.
echo $indexedArray[0]; // Access the value at the 0th index.
Or even..
$indexedArray = [0, 10, 12, 8];
echo $indexedArray[3]; // Outputs 8.
If you want to use non integer keys with your array, you simply specify them.
$assocArray = ['foo' => 'bar'];
echo $assocArray['foo']; // Outputs bar.