How to extract a data from a php array

Asked

Viewed 402 times

0

Good people, good my little script for posts checks if it already exists, if yes it does not record, if not it writes in the comic. I want to put a like system on it, so I created a table but for me to identify the post and such I need the post ID.. So far so good.. If you look at it in "print_r($idcheck);" it returns me an array with the id and the post, but I must extract the id in string form, but due to my lack of knowledge up to ag I could not solve this..

Array ( [0] => Array ( [id] => 62 [content] => jjjjjjjjjjjjjjjjjjj ) ) I only need the id, but when I place echo $idcheck["id"] or idcheck[0] error..

        $status = 1;

        if( isset( $_POST['publicar'] ) ){

            date_default_timezone_set('America/Sao_Paulo');
            $form['data']       = date('Y-m-d H:i:s');
            $form['conteudo']   = str_replace( '\r\n', "\n", DBEscape( trim( $_POST['conteudo'] ) ));
            $form['status']     = DBEscape( strip_tags( trim( $status ) ) );
            if( empty( $form['conteudo'] ) )
                echo'';
            else {

                $dbCheck = DBRead( 'posts', "WHERE conteudo = '". $form['conteudo'] ."'" );

                if( $dbCheck )
                    echo '<script>alert("Desculpe, mas já contaram esse segredo!");</script>';
                else {

                    if( DBCreate( 'posts', $form ) ){
                        $idcheck = DBRead( 'posts', "WHERE conteudo = '". $form['conteudo'] ."'", 'id, conteudo');  
                        var_dump($idcheck);
                        echo '<pre>';
                        print_r($idcheck);
                        echo '</pre>';
                        //echo '<script>document.getElementById("myP").style.visibility = "visible";</script>';
                        echo '<script>alert("Seu segredo foi postado com sucesso!");</script>';
                    }
                    else
                        echo '<script>alert("Desculpe, ocorreu um erro...");</script>';
                }
            }

        }
?>

1 answer

0


Try the following:

$id = (string)$idcheck[0]['id'];

From what I’ve seen, this $idcheck variable is a multidimensional array. I also suggested to force the value to string, to make sure that the $id variable will receive the value as a string.

  • gave right!! thanks.. I also found another way, to make a foreach inside another

  • It also works to make two loops... but if the variable is small in this way and does not contain much data, accessing the value directly may be better. Anyway, good luck to you!

  • Thanks, you’ve helped a lot!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.