1

I have one small problem and can't move on.

I wrote this PHP code:

 $d=array();
 foreach(range(0, 3) as $rs) {
    foreach(range(0, 5) as $c){

       //here is working php code to generate '$randomRs' by '$rs' and '$c' vars..

       $d[] = array('rs'.$rs => array('c'.$c => $randomRs));

    }
}
echo json_encode($d);

Now JSON output is:

[{"rs0":{"c0":"bl"}},{"rs0":{"c1":"pl"}},{"rs0":{"c2":"bl"}},{"rs0":{"c3":"pl"}},{"rs0":{"c4":"pl"}},{"rs0":{"c5":"wd1"}},{"rs1":{"c0":"lk"}},{"rs1":{"c1":"gr"}},{"rs1":{"c2":"lk"}},{"rs1":{"c3":"gr"}},{"rs1":{"c4":"lk"}},{"rs1":{"c5":"gr"}},{"rs2":{"c0":"u1"}},{"rs2":{"c1":"u1"}},{"rs2":{"c2":"u1"}},{"rs2":{"c3":"wt"}},{"rs2":{"c4":"u1"}},{"rs2":{"c5":"u1"}},{"rs3":{"c0":"u1"}},{"rs3":{"c1":"u1"}},{"rs3":{"c2":"u1"}},{"rs3":{"c3":"u1"}},{"rs3":{"c4":"cl"}},{"rs3":{"c5":"ir"}}]

Which is wrong. I need to achieve this result (don't mind values) :

{
"rs0":{
   "c0":"pl",
   "c1":"pl",
   "c2":"pl",
   "c3":"pl",
   "c4":"pl"
},
"rs1":{
   "c0":"pl",
   "c1":"pl",
   "c2":"pl",
   "c3":"pl",
   "c4":"pl"
}
and so on...

Please show me what i am doing wrong and how can I complete this?

6
  • You create and encode an array, your desired output shows an encoded object. Commented Jan 31, 2017 at 21:00
  • I thing you need this instead: $d['rs'.$rs]['c'.$c] = $randomRs; Commented Jan 31, 2017 at 21:02
  • It's obvious now :D Commented Jan 31, 2017 at 22:55
  • @arkascha hey again, I wonder how to count values in that php array. I want to count for example how many "pl" in that array. I have tried many ways, but none seems to work. Could you help me? Commented Feb 1, 2017 at 20:45
  • Short hint: take a look at the array_walk function for that. But in general: please ask a new question for new stuff. Thanks. Commented Feb 1, 2017 at 20:47

1 Answer 1

1
$d=array();
foreach(range(0, 3) as $rs) {
    foreach(range(0, 5) as $c){

        //here is working php code to generate '$randomRs' by '$rs' and '$c' vars..

        $d['rs'.$rs]['c'.$c] = $randomRs;

    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I am too tired when coding :D You saved my time!
I wonder how to count values in that php array. I want to count for example how many "pl" in that array. I have tried many ways, but none seems to work. Could you help me?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.