I am trying to make a JSON object out of multiple Array in PHP.
$a = array("Wis","Dex","Cha" );
$b = array(1,2,2);
$c = array("Perception","Stealth","Intimidation");
$d = array(8,5,1);
and I'm trying to get a bunch of JSON out of it such as this:
{ $c[0]:$d[0], "Stat":$a[0], "Multiplier:$b[0] };
and to get all those JSON and turn them in a string. But I've been trying to understand how json_encode works, but I cannot figure it out. I am hoping someone will be able to explain to me how to manipulate these values to turn them in JSON.
You can manually create the desired array using a for loop, then use json_encode on it. You have to be sure that the four arrays are the same size though.
$n = count($a);
$combined = array();
for ($i = 0; $i < $n; $i++) {
$entry = array();
$entry[$c[$i]] = $d[$i];
$entry["Stat"] = $a[$i];
$entry["Multiplier"] = $b[$i];
$combined[$i] = $entry;
}
$json = json_encode(combined);
How do you want the data to come out? As a JSON array of JSON object strings, or each string individually?
<?php
$a = array("Wis","Dex","Cha" );
$b = array(1,2,2);
$c = array("Perception","Stealth","Intimidation");
$d = array(8,5,1);
$data[$c[0]]=$d[0];
$data["Stat"]=$a[0];
$data["Multiplier"]=$b[0];
print(json_encode($data));
?>
Will give you something like
{"Perception":8,"Stat":"Wis","Multiplier":1}
If you want an array of those, then a few changes:
<?php
$a = array("Wis","Dex","Cha" );
$b = array(1,2,2);
$c = array("Perception","Stealth","Intimidation");
$d = array(8,5,1);
for($i=0;$i<count($a);$i++){
$data[$i][$c[$i]]=$d[$i];
$data[$i]["Stat"]=$a[$i];
$data[$i]["Multiplier"]=$b[$i];
}
print(json_encode($data));
?>
Which will give you something like
[{"Perception":8,"Stat":"Wis","Multiplier":1},
{"Stealth":5,"Stat":"Dex","Multiplier":2},
{"Intimidation":1,"Stat":"Cha","Multiplier":2}]
Related
I'm having some doubt doing some for each loop, so i have an immense variable names ranging from $a1 - $a120
What I'm trying to do is doing a for each loop from where I can get each of thoose by using an indexing system.
$a116= "N69";
$a117= "V52";
$a118= "V53";
$a119= "V54";
$a120= "V55";
# FIM
for ($i = 0; $i <= 119; ++$i) {
$var = ${"a".$i}; // This is what i need to learn to do
$sheet->setCellValue($var, $array[$i]); // the array is other information im inserting to the file
}
It is not good for the loops. But you can use it, if you can not change your codes.
I just added
$var_name="a".$i;
$var = $$var_name;
And the full code is below.
$a116= "N69";
$a117= "V52";
$a118= "V53";
$a119= "V54";
$a120= "V55";
# FIM
for ($i = 0; $i <= 119; ++$i) {
$var_name="a".$i;
$var = $$var_name; // This is what i need to learn to do
$sheet->setCellValue($var, $array[$i]); // the array is other information im inserting to the file
}
You should update the code to use an array.
$data = [];
$data["a116"] = "N69";
$data["a117"] = "V52";
$data["a118"] = "V53";
$data["a119"] = "V54";
$data["a120"] = "V55";
Now you can use a foreach loop getting the key/value pairs
foreach($data as $key => $value){
$sheet->setCellValue($key, $value);
}
I am working on a small php script, currently i have an array like this
[0] yassine#m, [1] yassine#f, [2] Dolmi#m , [3] yassine#l
I want PHP to check if there is a duplicated element (yassine in this case) and return something like this.
[0] yassine , [1] Dolmi#m
array_unique won't work. And i really don't have any clue how to solve this. If looked for a solution on the internet but doesnt seem to find it. Anyone can help Please ?
I think this may work for you.
First sort array by value, then use combination of substr(), strpos() and array_push() to create new array according to your need
then remove duplicate value using array_unique()
<?php
$oldarray = array("suman#1","suman#2","suman#3","sujan#1","suresh#2","");
// first sort array by value so matching value comes together
asort($oldarray);
$newarray = array();
$count = count($oldarray);
for($i=0; $i < $count-1; $i++){
$a = $oldarray[$i];
$b = $oldarray[$i+1];
if($i == 0)
$c = "";
else
$c = $oldarray[$i-1];
if(substr($a,0,strpos($a,"#")) == substr($b,0,strpos($b,"#")) || substr($a,0,strpos($a,"#")) == substr($c,0,strpos($c,"#")) ){
array_push($newarray,substr($a,0,strpos($a,"#")));
}
else
array_push($newarray,$a);
}
print_r($oldarray);
// now remove duplicate value from new array
$newarray = array_unique($newarray);
print_r($newarray);
?>
Check following solution
http://ideone.com/fork/kJlLbs
<?php
function generateUniqueList ($arr){
$ret = array();
foreach ($arr as $value) {
$key = explode("#", $value)[0];
if (array_key_exists($key, $ret)) {
$ret[$key] = $key;
}
else {
$ret[$key] = $value;
}
}
return array_values($ret);
}
$arr = array("yassine#m","yassine#f","Dolmi#m", "yassine#l");
$list = generateUniqueList ($arr);
print_r($list);
Before you go all duplicate of "question" on me. Please read out the situation.
In my application I build objects based on data from the database. However sometimes I happens that the same database entry is read twice due to a LIKE statement in my sql query(which runs once for each user in the group of the current user). Due to this it can happen that multiple equal objects are created which will not be considered duplicates according to array_unique.
//These objects are equal but are not duplicates.
//And these cases need to be removed from the array.
$z = new Obj(1,2,3);
$y = new Obj(1,2,3);
//code example
$e = array();
while($row = mysqli_fetch_array($result)){ //result is result from query.
$a = $row['var1']; //obtains data from result
$b = $row['var2'];
$c = $row['var3'];
$d = new Obj($a, $b, $c); //Creates new object
array_push($e, $d); //Holds all objects
}
class Obj{
public $a;
public $b;
public $c;
public function __construct($a, $b, $c){
$this->a = $a;
$this->b = $b;
$this->c = $c;
}
}
//This could work but it is a slow(forbidden) algorithm.
foreach($e as $f){
foreach($e as $g){
//REMOVE DUPLICATES
}
}
//This wont work because technically the 2 duplicates are 2 different objects.
//And not duplicates right?
$e = array_unique($e)
So the question is: Is there a simple or faster way to remove any duplicates from this array instead of using a double loop?
Maybe something like this:
$e = array();
$ids = array();
while($row = mysqli_fetch_array($result)){ //result is result from query.
$a = $row['var1']; //obtains data from result
$b = $row['var2'];
$c = $row['var3'];
$d = new Obj($a, $b, $c); //Creates new object
$id = base64_encode(serialize($d));
if (! in_array($id, $ids)) {
array_push($e, $d);
array_push($ids, $id);
}
}
I want to add two element in an array. The first one is the key and the second is the value. But I want to add it dynamically. I want to do it like the following code:
$arr="";
for( $i=0;$i<20;$i++ ) {
$arr[$i]=arr($i=>$i+1);
array_push($arr[$i]);
}
print_r($arr);
But of course it don't work. Could anyone tell me how to do it ?
Maybe you are trying to do this:
$arr = array(); // use array() instead of empty string
for( $i=0; $i<20; $i++ ) {
$arr[$i]= $i + 1;
}
print_r($arr);
$arr must be an array not string try this
$arr= array();
instead of
$arr="";
Not sure what you mean by all this, but you didn't really define the arrays correctly.
$arr = array();
for($i=0;$i<20;$i++) {
$arr[$i] = $i + 1;
array_push($arr[$i]);
}
print_r($arr);
Like answered above, you must use the array() function.
Try this way
$arr = array();
for($i=0;$i<20;$i++) {
$arr[$i] = $i+1;
}
print_r($arr);
This is tested and working
<?php
$stack = array("");
for($i=0;$i<20;$i++) {
array_push($stack, $i);
}
print_r($stack);
?>
this code will allow you to do what you request, unless I understood your requirement wrong?
Let me know if this is any help :)
If you are trying to create a numbered list, then use this instead:
<?php
$stack = array("0");
for($i=1;$i<20;$i++) {
array_push($stack, $i);
}
print_r($stack);
?>
Checkout the php manual: http://uk3.php.net/array_push
Josh.
I need to output a JSON response using PHP5 that looks similar to the following:
{"success": true, "years": [{"yearnumber": 2012},{"yearnumber": 2013},...]}
I have gotten as far as:
$rt = array();
$rt["success"] = true;
$rt["years"] = array();
for ($i=date('Y') ; $i < (date('Y')+21) ; $i++) {
$rt['years'][]= 'yearnumber:'.$i;
}
echo json_encode($rt);
Ofcourse this is not the proper way to achieve my goal - and it obviously doesn't produce the desired results.
I am fairly new to PHP programming and could use a little push here. Thanks.
To get this (The closest valid JSON that would be what I think you want):
{"success":true, "years":[2012,2013,...]}
You can use:
$rt = array();
$rt["success"] = true;
$rt["years"] = array();
for ($i=intval(date('Y')) ; $i < (date('Y')+21) ; $i++) {
$rt['years'][]= $i;
}
echo json_encode($rt);
//{"success":true,"years":[2012,2013,2014,2015,2016,2017,2018,2019,2020,2021,2022,2023,2024,2025,2026,2027,2028,2029,2030,2031,2032]}
For "years": [{"yearnumber": 2012}, {"yearnumber": 2013}]
You can use:
$rt = array();
$rt["success"] = true;
$rt["years"] = array();
for ($i=intval(date('Y')) ; $i < (date('Y')+21) ; $i++) {
$rt['years'][]= array("yearnumber" => $i);
}
echo json_encode($rt);
//{"success":true,"years":[{"yearnumber":2012},{"yearnumber":2013},{"yearnumber":2014},{"yearnumber":2015},{"yearnumber":2016},{"yearnumber":2017},{"yearnumber":2018},{"yearnumber":2019},{"yearnumber":2020},{"yearnumber":2021},{"yearnumber":2022},{"yearnumber":2023},{"yearnumber":2024},{"yearnumber":2025},{"yearnumber":2026},{"yearnumber":2027},{"yearnumber":2028},{"yearnumber":2029},{"yearnumber":2030},{"yearnumber":2031},{"yearnumber":2032}]}
Though it appears redundant to me
This
{"success":true, "years":["yearnumber":2012,"yearnumber":2013,...]}
is not valid JSON. Arrays ([]) can't have keys in them, only values. The best solution (in this scenario) is to just cut they keys since they're all the same anyway (See Esailija's answer)
Another way would be to create an array of objects like this
{"success":true, "years":[{"yearnumber":2012},{"yearnumber":2013},...]}
To achieve that from PHP:
$rt = array();
$rt["success"] = true;
$rt["years"] = array();
for ($i=intval(date('Y')) ; $i < (date('Y')+21) ; $i++) {
$rt['years'][] = array('yearnumber' => $i);
}
echo json_encode($rt);