Rich fiifi Rich fiifi - 6 months ago 17
PHP Question

fetching one value from each key in an associated array

I have the following array

array(
'messages' => array(
0 => array(
'id' => '3',
'subject' => 'what did you say last night?',
'message' => 'your mother wai',
'from' => '13',
'to' => '1',
'from_viewed' => '0',
'to_viewed' => '0',
'from_deleted' => '0',
'to_deleted' => '0',
'from_vdate' => NULL,
'to_vdate' => NULL,
'from_ddate' => NULL,
'to_ddate' => NULL,
'created' => '2016-05-14 14:02:12',
) ,
1 => array(
'id' => '2',
'subject' => 'this is new',
'message' => 'hello guy',
'from' => '11',
'to' => '1',
'from_viewed' => '0',
'to_viewed' => '0',
'from_deleted' => '0',
'to_deleted' => '0',
'from_vdate' => NULL,
'to_vdate' => NULL,
'from_ddate' => NULL,
'to_ddate' => NULL,
'created' => '2016-05-14 13:59:56',
) ,
2 => array(
'id' => '1',
'subject' => 'hello boy.',
'message' => 'i love this too much . what do you think about making this happen for tomorrow? already then . good bye',
'from' => '11',
'to' => '1',
'from_viewed' => '0',
'to_viewed' => '0',
'from_deleted' => '0',
'to_deleted' => '0',
'from_vdate' => NULL,
'to_vdate' => NULL,
'from_ddate' => NULL,
'to_ddate' => NULL,
'created' => '2016-05-14 13:54:02',
) ,
) ,
)


All i want to do is to take the 'FROM' value of every key in the array(in this case it is - 13, 11 ,11) and then send them to the database to retrieve information like their name and avatar , in codeigniter.

UPDATE

I TRIED THE FOLLOWING AND IT GAVE ME 11,11,13, (with a comma at the back).

$from = $messages['messages'];


for ($col = 0; $col < 3; $col++) {
echo $messages['messages'][$col]['from'].",";
}


Besides , i dont want to determine how many values it should echo. I want it to echo as long as it exists.

Answer

you may use this

$t = array(
    'messages' => array()
 )
 /// your array ......

$from = '';
foreach($t['messages'] as $k => $m){
    if($k == 0){
        $from = $m['from'];
    }else{
        $from .= ','.$m['from'];
    }
}
echo $from;

It will output as 13,11,11. But if you need array of those values then you may use following

$from = array();
foreach($t['messages'] as $k => $m){
        $from[] = $m['from'];

}
print_r($from);