Find item in array

Asked

Viewed 75 times

-3

I wonder if my code is right. because I would like to take the linked name with which it is linked with the code(id), where mmot receives a number to be searched within the array. Thank you

    $url = file_get_contents('https://parallelum.com.br/fipe/api/v1/motos/marcas');

    function get_page($url){

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;

        foreach ($result as $key) {
            if($key['codigo'] == $mmot){
                $mmot = $key['$mmot']['nome']; 
            }
        }

    }

    $marcafinal = $mmot;
  • 3

    if you give the Return to $result it will terminate the ai function without running the foreach

  • Hi, I tried to do what you said and took the Return, but keeps returning me no value :(

  • I posted an example that tests, if you want to test there, I tested and ok

4 answers

1

This way is right and you don’t even need to use Curl, if you just need to edit the way you think best, example working:

 <?php
$url = file_get_contents('https://parallelum.com.br/fipe/api/v1/motos/marcas');
$mmot = "60";

function get_page($url,$mmot){
    $result = json_decode($url,true);

    foreach($result as $key)
    {
        if($key['codigo'] == $mmot)
        {
            return $key['nome'];
        }
    }

}

$marcafinal = get_page($url,$mmot);

echo "Valor: ".$marcafinal;  

?>
  • Hi I used your example and I got this error here Warning: file_get_contents(https://parallelum.com.br/fipe/api/v1/carros/marcas/70/models/): failed to open stream: HTTP failed request! HTTP/1.1 404 Not Found in Fatal error: Cannot redeclare get_page() (Previously declared in C: xampp htdocs plus insert.php:59) in

  • is that this link (https://parallelum.com.br/fipe/api/v1/carros/marcas/70/models/) does not exist on the site, it does not return anything but a 404 error that has not been found, this link (https://parallelum.com.br/fipe/apiv1/motos/marks) it returns a perfect json, try to see if they haven’t changed the api link

  • ta, thank you. :)

  • I took a look at the api and saw that the code 70 does not exist, if you test this link (https://parallelum.com.br/fipe/api/v1/carros/marcas) you can see all brands, and if you use it this way (https://parallelum.com.br/fipe/apiv1/carros/marcas/59/models) where 59 is a valid code, it will appear the templates of this code

0

Your code is full of problems, but I’ll try to show you one by one here. I understand you’re making a call by curl and who wants to manipulate the answer, so let’s go:

// $url está sendo declarado fora do escopo de onde será usado, no caso, o seu método
$url = file_get_contents('https://parallelum.com.br/fipe/api/v1/motos/marcas');

// essa função não foi chamada em lugar nenhum
function get_page($url){ // $url é redeclarado como alterador de parametro e ofusca a variável ali em cima

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    $result = curl_exec($ch);
    curl_close($ch);

    // está retornando o corpo da response, o bloco for ali em baixo não será executado
    return $result;

    // você sabe o que está vindo no $result para enumerar ele?
    foreach ($result as $key) {

        // quem é codigo e quem é $mmot (que nem foi declarado)?
        if($key['codigo'] == $mmot){

            // aqui nunca será processado, pois será atirado um erro na linha acima.
            // mas se $mmot fosse declarado, a linha abaixo também não faria lógica, já que está procurando a chave '$mmot' na coleção $key.
            $mmot = $key['$mmot']['nome']; 
        }
    }

}

$marcafinal = $mmot;

Your question is unclear and the refactoring of your code would be approximately that:

$url_endpoint = file_get_contents('https://parallelum.com.br/fipe/api/v1/motos/marcas');

function get_page($url){

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    $result = curl_exec($ch);
    curl_close($ch);

    $responseValues = json_decode($result, true); // isso se sua API for JSON

    // Você precisa associar esse $mmot a algo, não pode deixar ele vago e sem declaração.
    $mmot = 0;
    $returnValue = null;

    foreach ($result as $key) {
        if($key['codigo'] == $mmot){
            $returnValue = $key['nome']; 
        }
    }

    return $returnValue;
}

$marcafinal = get_page($url_endpoint);

I did so taking into account that $mmot is a code that leads to the JSON object that searches for nome. Thus, you must specify $mmot in the method I left clear there, or pass as a parameter.

-2

Ta wrong, you are declaring the $mmot inside the if and using it in condition, I believe you have to declare it before

  • the $mmot ta declared before yes, I declared it before doing function.

  • @Victoraugusto So maybe you’re missing it as a function parameter (as shown in other answers here) or place within the function an indication that $mmot is global => global $mmot;, NOTE. It is worth you edit your question to put the information you put in this comment.

-2

Code tested and working:

<?php

function get_page($url){

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function procuraMmot($mmot) {
    $retorno = '';
    $url = 'https://parallelum.com.br/fipe/api/v1/motos/marcas';
    $resultado = json_decode(get_page($url), true);

    foreach ($resultado as $value) {
        if($value['codigo'] == $mmot){
            $retorno = $value['nome']; 
        }
    }
    return $retorno;
}

$resultado = procuraMmot(60);
echo "resultado: $resultado";

Browser other questions tagged

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