PHP calling function within a class

I'm writing my own php class and I have multiple functions within the class. Something like this:

class JSON_API_Hello_Controller {

    public function test_cat(){
        global $json_api;

        $posts = $json_api-introspector-get_posts(array( 'cat' = 3));
        return $this-posts_object_result_bycat($posts);
    }

    public function test_cat1() {
        global $json_api;

        $posts = $json_api-introspector-get_posts(array( 'cat' = 2));
        return $this-posts_object_result_bycat($posts);
    }

    protected function posts_object_result_bycat($posts) {
        global $wp_query;

        return array(
            'count' = count($posts),
            'pages' = (int) $wp_query-max_num_pages,
            'posts' = $posts
        );
    }

    public function mix_cat(){

        $first_cat = $this-test_cat();
        $second_cat = $this-test_cat1();
        $json1 = json_decode($first_cat , true);
        $json2 = json_decode($second_cat, true);
        $final_array = array_merge($json1, $json2);
        // Finally encode the result back to JSON.
        $final_json = json_encode($final_array);
    }

} 

I tried something like this. I want to call the test_cat() and test_cat1() function in other function like mix_cat() inside the same class. Both function (test_cat() test_cat1()) return the json object. Both return json object will be join in mix_cat() function. Please suggest me How can I call the testcat() test_cat1() function in mix_cat() and join the result of both function in mix_cat() function.

Topic plugin-json-api oop php plugin-development Wordpress

Category Web


You can merge this two json objects via array_merge. But you must decode before to a array. You have this inside your example, below as single source function. This should get the merged json object.

A example function, usable for your mix_cat()method.

function mergeToJSON( $obj1, $obj2 ) {

    $json1 = $this->test_cat();
    $json2 = $this->test_cat1();

    if ( $json1 === FALSE || $json2 === FALSE ) {
        return;
    }

    $array1 = json_decode( $json1, TRUE );
    $array2 = json_decode( $json2, TRUE );
    $data = array_merge( $array1, $array2 );

    return json_encode( $data );
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.