array to string concatenation [duplicate] - php

This question already has answers here:
Return single column from a multi-dimensional array [duplicate]
(7 answers)
Closed 5 years ago.
I got the next array:
Array (
[0] => Array ( [email] => xasxxxxxx#yahoo.com [btc] => 0.00287896 [tn] => 6.615 [address] => 2BY4HM [status] => pending )
[1] => Array ( [email] => xxxxx#yahoo.com [btc] => 0.04000 [tokens_given] => 5 [address] => xxXXxxxxxaaaxxXs [status] => pending )
[2] => Array ( [email] => xsxxxx#yahoo.com [btc] => 0.04000 [tokens_given] => 5 [address] => xxXXxxxxxaaaxxXs [status] => pending )
[3] => Array ( [email] => xssasas5#yahoo.com [btc] => 0.04000 [tokens_given] => 5 [address] => xxXXxxxxxaaaxxXs [status] => pending )
[4] => Array ( [email] => xxxxxx#yahoo.com [btc] => 0.04000 [tokens_given] => 5 [address] => xxXXxxxxxaaaxxXs [status] => pending )
)
How am I supposed to get all 'address'es in a variable as a string separated by comma?
something like this
$string = "1stadress, 2ndaddress, 3ndadress' etc
I tried:
$comma_separated = implode(",", $row['address']); // where $ row is the array above
and it failed.

You can use array_column and implode
echo implode(',',array_column($myarray,'address'));

Loop though array and collect the relevant members, I'd perefer using untermidiate array this way it can be reused if needed later
$buffer = [];
foreach($myArray as $id=>$data){
$buffer[] = $data['address'];
}
$output = implode(',',$buffer);

Related

How to add one array to another array [duplicate]

This question already has answers here:
PHP append one array to another (not array_push or +)
(11 answers)
Closed 3 years ago.
I have two array, i want to convert it with one array with whole data.
My array format is here
$fromData=array('id' => '004','shapeid' => 'circle','x' =>'360','y' => '560', 'tooltext' => 'vivek','labelpos' => 'bottom');
$ToData=array('id' => '005','shapeid' => 'triangle','x' =>'480','y' => '980', 'tooltext' => 'kimi','labelpos' => 'top');
I wanna got whole data in one array.
Thanks
you can use array_merge_recursive
$fromData=array('id' => '004','shapeid' => 'circle','x' =>'360','y' => '560', 'tooltext' => 'vivek','labelpos' => 'bottom');
$ToData=array('id' => '005','shapeid' => 'triangle','x' =>'480','y' => '980', 'tooltext' => 'kimi','labelpos' => 'top');
$newdata= array_merge_recursive($fromData,$ToData);
output will be
Array
(
[id] => Array
(
[0] => 004
[1] => 005
)
[shapeid] => Array
(
[0] => circle
[1] => triangle
)
[x] => Array
(
[0] => 360
[1] => 480
)
[y] => Array
(
[0] => 560
[1] => 980
)
[tooltext] => Array
(
[0] => vivek
[1] => kimi
)
[labelpos] => Array
(
[0] => bottom
[1] => top
)
)
This can be done based on what #Ajith is suggesting in above comment
$result[] = $fromData;
$result[] = $ToData;
You can check this implementation here, https://3v4l.org/0QR56

Parse XML to Array with SimpleXML

I've that xml structure retrieving from device
<packet>
<info action="fiscalmemory" fiscalmemorysize="1048576" recordsize="464" fiscal="1" uniqueno="ABC12345678" nip="123-456-78-90" maxrecordscount="2144" recordscount="7" maxreportscount="1830" reportscount="4" resetmaxcount="200" resetcount="0" taxratesprglimit="30" taxratesprg="1" currencychangeprglimit="4" currencychangeprg="0" fiscalstartdate="dd-mm-yyyy hh:dd:ss" fiscalstopdate="dd-mm-yyyy hh:dd:ss" currencyname="PLN" />
<ptu name="A" bres="Nobi">123.23</ptu>
<ptu name="B">123.23</ptu>
<ptu name="D">8</ptu>
<sale>999.23</sale>
</packet>
simpleXml does't see ptu's attributes
$array = simplexml_load_string($xml);
print_r($array);
It prints
SimpleXMLElement Object
(
[info] => SimpleXMLElement Object
(
[#attributes] => Array
(
[action] => fiscalmemory
[fiscalmemorysize] => 1048576
[recordsize] => 464
[fiscal] => 1
[uniqueno] => ABC12345678
[nip] => 123-456-78-90
[maxrecordscount] => 2144
[recordscount] => 7
[maxreportscount] => 1830
[reportscount] => 4
[resetmaxcount] => 200
[resetcount] => 0
[taxratesprglimit] => 30
[taxratesprg] => 1
[currencychangeprglimit] => 4
[currencychangeprg] => 0
[fiscalstartdate] => dd-mm-yyyy hh:dd:ss
[fiscalstopdate] => dd-mm-yyyy hh:dd:ss
[currencyname] => PLN
)
)
[ptu] => Array
(
[0] => 123.23
[1] => 123.23
[2] => 8
)
[sale] => 999.23
)
As we can see ptu doesn't contain attributes :/
I also tried parse it with recursive function because children also may contain chilren but without success :/
Could anybody point to me why SimpleXML doesn't take ptu's attributes and also share any parsing function?
Thanks in advance.
edited
As regards Nigel Ren I made that function
function parseXMLtoArray($xml){
$x = simplexml_load_string($xml);
$result = [];
function parse($xml, &$res){
$res['name'] = $xml->getName();
$res['value'] = $xml->__toString();
foreach ($xml->attributes() as $k => $v){
$res['attr'][$k] = $v->__toString();
}
foreach($xml->children() as $child){
parse($child, $res['children'][]);
}
}
parse($x, $result);
return $result;
}
$resArray = parseXMLtoArray($rawXml);
print_r($resArray);
this returns such array
Array
(
[name] => packet
[value] =>
[attr] => Array
(
[crc] => BKJFKHKD54
)
[children] => Array
(
[0] => Array
(
[name] => info
[value] =>
[attr] => Array
(
[action] => fiscalmemory
[fiscalmemorysize] => 1048576
[recordsize] => 464
[fiscal] => 1
[uniqueno] => ABC12345678
[nip] => 123-456-78-90
[maxrecordscount] => 2144
[recordscount] => 7
[maxreportscount] => 1830
[reportscount] => 4
[resetmaxcount] => 200
[resetcount] => 0
[taxratesprglimit] => 30
[taxratesprg] => 1
[currencychangeprglimit] => 4
[currencychangeprg] => 0
[fiscalstartdate] => dd-mm-yyyy hh:dd:ss
[fiscalstopdate] => dd-mm-yyyy hh:dd:ss
[currencyname] => PLN
)
)
[1] => Array
(
[name] => ptu
[value] => 123.23
[attr] => Array
(
[name] => A
)
)
[2] => Array
(
[name] => ptu
[value] => 123.23
[attr] => Array
(
[name] => B
)
)
[3] => Array
(
[name] => ptu
[value] => 8
[attr] => Array
(
[name] => D
)
)
[4] => Array
(
[name] => sale
[value] => 999.23
)
)
)
Is this correct?
Thanks again Nigel
When loading with SimpleXML, using print_r() gives only an idea of the content and doesn't have the full content. If you want to see the full content then use ->asXML()...
$array = simplexml_load_string($xml);
echo $array->asXML();
To check the attributes of <ptu> element, (this just gives the first one)...
echo $array->ptu[0]['name'];
This uses ->ptu to get the <ptu> element and takes the first one [0] and then takes the name attribute using ['name'].

Echo arrays in foreach loop codeigniter

I've been using codeigniter for years but there's a really big gap in between so i always find myself in situations where i forgot how to do things and its almost midnight here so my brain isn't working fast. Can someone show me how to echo the array i have and explain to me how they are processed in the foreach loops?
I have this code in my model to take the rows in 2 tables.
public function tag_genre(){
$result['tag'] = $this->db->get('tags')->result_array();
$result['genre'] = $this->db->get('genre')->result_array();
return $result;
}
And I have this in my controller
public function view_publish_story(){
$data = array('tag_genre' => $this->story_model->tag_genre(), 'title' => "New Story");
$this->load->view('template/header',$data);
$this->load->view('template/navbar');
$this->load->view('pages/storypublish',$data);
$this->load->view('template/footer');
}
I used print_r in my view and this is the result. Seeing this just confuses me more. It's been atleast 2 years since i even dealt with foreach loops.
Array ( [tag] => Array ( [0] => Array ( [tag_id] => 1 [tag_name] =>
LitRPG ) [1] => Array ( [tag_id] => 2 [tag_name] => Virtual Reality )
[2] => Array ( [tag_id] => 3 [tag_name] => Cyberpunk ) [3] => Array (
[tag_id] => 4 [tag_name] => Reincarnation ) [4] => Array ( [tag_id] =>
5 [tag_name] => Summoned Hero ) [5] => Array ( [tag_id] => 6
[tag_name] => Martial Arts ) [6] => Array ( [tag_id] => 7 [tag_name]
=> Slice of Life ) [7] => Array ( [tag_id] => 8 [tag_name] => Overpowered ) [8] => Array ( [tag_id] => 9 [tag_name] => Non-Human )
[9] => Array ( [tag_id] => 10 [tag_name] => Anti-hero ) ) [genre] =>
Array ( [0] => Array ( [genre_id] => 1 [genre_name] => action ) [1] =>
Array ( [genre_id] => 2 [genre_name] => adventure ) [2] => Array (
[genre_id] => 3 [genre_name] => comedy ) [3] => Array ( [genre_id] =>
4 [genre_name] => Drama ) [4] => Array ( [genre_id] => 5 [genre_name]
=> Fantasy ) [5] => Array ( [genre_id] => 6 [genre_name] => Historical ) [6] => Array ( [genre_id] => 7 [genre_name] => Horror ) [7] => Array
( [genre_id] => 8 [genre_name] => Psychological ) [8] => Array (
[genre_id] => 9 [genre_name] => Romance ) [9] => Array ( [genre_id] =>
10 [genre_name] => Sci-fi ) [10] => Array ( [genre_id] => 11
[genre_name] => Mystery ) [11] => Array ( [genre_id] => 12
[genre_name] => Tragedy ) [12] => Array ( [genre_id] => 13
[genre_name] => Short Story ) [13] => Array ( [genre_id] => 14
[genre_name] => Satire ) ) )
I've been looking at various questions regarding arrays from assoc to multidimensional and other stuff. Then i finally visited php manual for foreach loop and i finally was able to echo the array. The problem now is that although it echoes my array it also has an error for each, i can probably fix the error part by declaring it as a defined variable. My question is, is there any other better way? or any improvement on how i made my array to make it cleaner or easier to print?
foreach($tag_genre as $key => $value){
foreach($value as $values){
echo $values['tag_name'];
}
}
UPDATE: i changed the way i made the array.
This is now my model:
public function get_tags(){
$query = $this->db->get('tags')->result_array();
foreach($query as $row){
$result[$row['tag_id']] = $row['tag_name'];}
return $result;
}
public function get_genre(){
$query = $this->db->get('genre')->result_array();
foreach($query as $row){
$result[$row['genre_id']] = $row['genre_name'];}
return $result;
}
and my controller:
public function view_publish_story(){
$data = array('tag' => $this->story_model->get_tags(), 'genre' => $this->story_model->get_genre(), 'title' => "New Story");
$this->load->view('template/header',$data);
$this->load->view('template/navbar');
$this->load->view('pages/storypublish',$data);
$this->load->view('template/footer');
}
and in my view:
<tr>
<div class="form-group">
<td><label for="genre">Genre</label></td>
<?php
foreach($genre as $genre_id => $genre_name){
echo "<td><label class='checkbox-inline'><input type='checkbox' value=''>".$genre_name."</label><td>";
}
?>
</div>
</tr>
My problem now is that, how do i fit all these into my table? I just ruined my table right now since i echoed them all in a single line. How do i do it so that it is printed in 3 columns?
foreach($tag_genre as $key => $value){
foreach($value as $values){
echo '<pre>';
echo $values['tag_name'];
}
}
this will format your array in a way you can read it and understand it.

Php Group array by value and count group item [duplicate]

This question already has answers here:
How to count array with group by
(2 answers)
Closed 4 months ago.
I am creating a notification system. That results shown below returns all notifications for a particular user. I want to group the array by 'notify_id' and also count each item in a group.
Such that I'll have :
"Jack Bill is now following you", John Doe commented on your post 2",
"John Doe and 2 others commented on your post 1"
Array ( [0] =>
Array ( [id] => 1
[user_id] => 10
[type] => follow
[notify_id] => 13
[notify_date] => 1483444712
[firstname] => Jack
[surname] => Bill
[picture] => )
[1] =>
Array ( [id] => 10
[user_id] => 10
[type] => comment
[notify_id] => 2
[notify_date] => 1482159309
[firstname] => John
[surname] => Doe
[picture] => )
[2] =>
Array ( [id] => 8
[user_id] => 10
[type] => comment
[notify_id] => 1
[notify_date] => 1482159219
[firstname] => John
[surname] => Doe
[picture] => )
[3] =>
Array ( [id] => 6
[user_id] => 16
[type] => comment
[notify_id] => 1
[notify_date] => 1482159129
[firstname] => James
[surname] => Canon
[picture] => )
[4] =>
Array ( [id] => 5
[user_id] => 14
[type] => comment
[notify_id] => 1
[notify_date] => 1482159079
[firstname] => Sharon
[surname] => Abba
[picture] => ) )
You have two questions, I will try to answer both of them:
I want to group the array by 'notify_id'...
Assuming your array name is $a:
$return = array();
foreach($a as $val) {
if (!isset($return[$val['notify_id']])) {
$return[$val['notify_id']] = array();
}
$return[$val['notify_id']][] = $val;
}
print_r($return); // <-- Your array is grouped by notify_id
... and also count each item in a group.
Now you have your grouped by notify_id in $return so:
foreach($return as $k => $v) {
echo count($v) . ' values are present for notify #' . $k;
// It will display something like: 10 values are present for notify #1
}
Hope it will help, good luck!

parse PHP array

I have managed to get to the stage where I have an array that looks like this. Used (zend_json to decode a json response)
Array
(
[response] => Array
(
[status] => ok
[userTier] => free
[total] => 10
[startIndex] => 1
[pageSize] => 10
[currentPage] => 1
[pages] => 1
[results] => Array
(
[0] => Array
(
[id] => lifeandstyle/series/cycling
[type] => series
[webTitle] => Cycling
[webUrl] => http://www.guardian.co.uk/lifeandstyle/series/cycling
[apiUrl] => http://content.guardianapis.com/lifeandstyle/series/cycling
[sectionId] => lifeandstyle
[sectionName] => Life and style
)
[1] => Array
(
[id] => sport/cycling
[type] => keyword
[webTitle] => Cycling
[webUrl] => http://www.guardian.co.uk/sport/cycling
[apiUrl] => http://content.guardianapis.com/sport/cycling
[sectionId] => sport
[sectionName] => Sport
)
How would I go about parsing only the elements that are [webTitle] and [webUrl]
Thanks!
You can't specifically parse only those parts, but you can iterate over the results and access them.
foreach ($val['response']['results'] as $result) {
$title = $result['webTitle'];
$url = $result['webUrl'];
// ...
}

Categories