1

I have a php json creater. That is a web service and I use it in android. I have sql datas, classes and would like run querys in clasess.

This is my json parser without classes.

<?php
 /$sql_query = blabla{

   $dolaplar= array();
    /* fetch object array */
    while ($obj = $result->fetch_object()) {
      // printf ("%d - %s - %s\n", $obj->id, $obj->tanim, $obj->tipi);
        $dolaplar[]= $obj;
    }
    $kodlanmis= json_encode($dolaplar);
    echo $kodlanmis;

    /* free result set */
    $result->close();
}

?>

And It's json data.

[
{
malzeme_id: "9",
malzeme_adi: "10 kohm direnc",
malzeme_miktari: "580"
},
{
malzeme_id: "8",
malzeme_adi: "Hdmi Kablosu",
malzeme_miktari: "128"
},
{
malzeme_id: "7",
malzeme_adi: "Kirmizi Led",
malzeme_miktari: "-653"
}
]

Here is classes.

<?php
class A {
    public $Message = "Success";
    public $MessageInfo = "";
    public $Payload = array();

    function  __construct(){
        for ( $i=3; $i-->0;){
            array_push($this->Payload, new B);
        }
    }
}

class B {
    public $a = 3;
    public $b = 4;
}

echo json_encode(new A);
?>

And I would like to see like that json data.

{
Message: "Success",
MessageInfo: "",
Payload: [
{
 malzeme_id: "9",
 malzeme_adi: "10 kohm direnc",
 malzeme_miktari: "580"
},
{
malzeme_id: "8",
malzeme_adi: "Hdmi Kablosu",
malzeme_miktari: "128"
},
{
malzeme_id: "7",
malzeme_adi: "Kirmizi Led",
malzeme_miktari: "-653"
}
]
}

I am not really good about php. Is it possible ?

1
  • Well, you need to pass the payload data in some way to Class A Commented Jan 4, 2016 at 0:09

1 Answer 1

2

You could add a parameter to your Class A and Class B constructors:

Class A:

class A {
    public $Message = "Success";
    public $MessageInfo = "";
    public $Payload = array();

    function  __construct($data){
        foreach ($data as $d) {
            array_push($this->Payload, new B($d));
        }
    }
}

Class B:

class B {
    public function __construct($data) {
        array_walk($data, function($value, $key){
            $this->$key = $value;
        });
    }
}

Then your call would look something like:

$data = $dolapla // ???
echo json_encode(new A($data));
Sign up to request clarification or add additional context in comments.

Comments

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.