How to use data from an Array without foreach

Asked

Viewed 865 times

1

I have a function in my Model:

public function get_learning_category_list() {

    $categorias = $this->db->select('t1.id, t1.title, t1.metadata, t1.meta_title, t1.description, t1.meta_description, t1.meta_spam, t1.url, t1.alt_img')
        ->from('learning_category t1')
        ->join('learning_rel_category t4', 't1.id = t4.category_id', 'left')
        ->join('learning t2', 't4.learning_id = t2.id', 'left')
        ->join('learning_rel_language t3', 't2.id = t3.learning_id', 'left')
        ->where('t3.language', $this->language)
        ->group_by('t1.id')
        ->get()->result_array();

    foreach ($categorias as $c) {

        $total = $this->db->select('count(learning_rel_language.learning_id) as total', false)
            ->from('learning')
            ->join('learning_rel_language', 'learning.id = learning_rel_language.learning_id', 'inner')
            ->join('learning_rel_category', 'learning.id = learning_rel_category.learning_id', 'inner')
            ->where('learning_rel_category.category_id', $c['id'])
            ->where('learning_rel_language.language', $this->language)
            ->group_by('learning_rel_language.language')->get()->first_row('array');

        $metadata = json_decode($c['metadata']);
        $tt = $c['title'];
        $url = $c['url'];

        if ($this->language != 'pt_br') {
            $tt = $metadata->{$this->language};
            $tt_pt_br = $c['title'];
        }

        $return[] = array('url' => $url, 'title'=>$tt, 'id'=>$c['id'], 'total'=>$total['total'], 'title_pt_br'=>$tt_pt_br);
    }

    return $return; //$categorias;
}

She gives me one Array with the list of learnings:

Array (  
    [0] => Array (  
        [url] =>  
        [title] => Cursos sobre como gerar leads qualificados  
        [id] => 2  
        [total] => 6  
        [title_pt_br] =>  
    )  
    [1] => Array (  
        [url] =>  
        [title] => Cursos de Social Media Marketing  
        [id] => 3  
        [total] => 2  
        [title_pt_br] =>  
    )  
    [2] => Array (  
        [url] =>  
        [title] => Cursos de SEO e otimização de sites  
        [id] => 4  
        [total] => 3  
        [title_pt_br] =>  
    )  
)

But I need to use the data from these learnings, the title, id, etc, in another function in the Model:

public function url_format_category($category, $lang_domin) {

    if (lang('abbr') == 'en_US')
        $lang_domin = 'en/';
    else if (lang('abbr') == 'es_US')
        $lang_domin = 'es/';

    $categorias = $this->learn->get_learning_category_list();
    print_r($categorias);

    foreach ($categorias as $cat) {

        print_r($cat);
        $cat = (object) $cat;

        if ($cat->title != '') {
            $return = strtolower(url_title($cat->title)).'-cmdo-'.$cat->id;
        }
        else {
            $return = 'cursos-de-marketing-digital-online-'.$cat->id;
        }   
        return $return;   
    } 
}

I’m doing a function to see if the site url is correct. This function (url_format_category) will define the format of the url, which in this case would be (O title). '-cmdo-'.(O id) So what I need is to retrieve the title and id according to the Learning you find.

I did so, but with the foreach always results in the same data regardless of which page I am.

How can I use this data Array without the foreach?

  • You have a return within a foreach!?

  • Yes, I know it’s wrong. I’m just starting to program. You know how I can do this?

  • I didn’t understand your problem. Put an example of the result you want to get

  • I need to use the data from the Array within another function. But with the foreach it always takes the data from the last Array item.

  • You realize you have one array into another? And so I need one foreach within another?

  • @bigown There is no way to use this data without foreach?

  • But the best way is this. I don’t understand why this obsession with not using the foreach.

  • I’ll explain my whole purpose to you to make it clearer. What I am doing is a function to see if the site url is correct, this function (url_format_category) will define the format of the url, which in this case would be (the title). '-cmdo-'.(The id) So what I need is to retrieve the title and id according to the Learning you find. Understand?

Show 3 more comments

2 answers

1

GWER, if you want $Return to return all the values assigned to the variable just concatenate example $Return.= then you return or print after foreach the variable if that you want

example:

public function url_format_category($category, $lang_domin) {
if (lang('abbr') == 'en_US')
    $lang_domin = 'en/';
else if (lang('abbr') == 'es_US')
    $lang_domin = 'es/';

$categorias = $this->learn->get_learning_category_list();
print_r($categorias);
foreach($categorias as $cat){
    print_r($cat);
    $cat = (object) $cat;
    if($cat->title != '') {

        //concatena  
        $return.= strtolower(url_title($cat->title)).'-cmdo-'.$cat->id;
    }else{
        //concatena  
        $return.= 'cursos-de-marketing-digital-online-'.$cat->id;
    }   

}
return $return; ou echo $result;
}
  • Solves part of my problem, but I need to take a specific value, not all

  • understand what would be the value of the foreach you want to take?

  • I’ll explain my whole purpose to you to make it clearer. What I’m doing is a function to see if the site url is correct, this function will define the format of the url, which in case would be (O title).'-cmdo-'.(O id) So what I need is to retrieve the title and id according to the Learning you find. Understand?

  • #GWER we go by part Voce want to check if this correct what in this your routine the variable would be to check if this correct url? It’s kind of confusing I don’t know if I have to validate url to then format or want to format it to then validate, see if I’m close to what you want

  • I shape it, then validate it

  • the end result of this formtacao would be something like this: "http://Domain/[title]-cmdo-id" like this? starting with http://?

  • Domain/[title]-cmdo-[id]

  • I just solved this case (with help of your answer included). Can you take a look at this question? http://answall.com/questions/57496/fun%C3%A7%C3%B5es-model-controller

  • blz guy already congratulations I’ll see

Show 4 more comments

1


Beast, you can search inside your array together with the functions array_search and array_column (This function only for the same or higher version of PHP 5.5.0 and if you are using a hosting enable this version if available).

I believe you can adapt your code with this solution.

For your role, I imagine you use slugs (unique and friendly urls), so follow an example below the example in the comments in the PHP manual.

// Buscar o nome do usuário com uid == 40489
<?php 
      $array = array(
                     array(
                           'uid' => '100',
                           'name' => 'Sandra Shush',
                           'url' => 'urlof100'
                      ),
                      array(
                            'uid' => '5465',
                            'name' => 'Stefanie Mcmohn',
                            'url' => 'urlof100'
                      ),
                      array(
                            'uid' => '40489',
                            'name' => 'Michael',
                            'url' => 'urlof40489'
                       )
               );

$key = array_search(40489, array_column($array, 'uid')); /*A partir do $array, retorna um array com a coluna 'uid' e dentro desse array, procura o valor 40489 e armazena o índice do array externo na variável $key. */

if($key != null && !empty($key)) // se não estiver vazio essa chave, pesquise direto.
    echo $array[$key]['name'];
else
    echo "sem dados";

http://php.net/manual/en/function.array-search.php#Hcom116635

http://ideone.com/NcNzkl

Browser other questions tagged

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