merging two elements of two arrays in php - php

Hello Everyone I have a Array in php like
array (size=2)
0 => string 'A6,A5,B12,B11,' (length=14)
1 => string 'B6,B5,B8,B7,' (length=12)
on var_dump($arr). How could I convert it to something like
array('A6,A5,B12,B11,B6,B5,B8,B7,')
in php.
here is what i'm doing eaxctly to get the above array
$id= "1";
$data['busInfo']= $this->dashboard_model->find_bus($id);
$data['reservationInfo'] = $this->dashboard_model->get_booked_seats_info($id);
$arr =array();
foreach ($data['reservationInfo'] as $reserved){
$seatBooked = $reserved->seats_numbers;
array_push($arr, $seatBooked);
}
var_dump($arr);
I'm using Codeigniter as my framework.

You can just append to a string, then create a single element array with that string (if you actually need an array):
$data['reservationInfo'] = $this->dashboard_model->get_booked_seats_info($id);
$str='';
foreach ($data['reservationInfo'] as $reserved){
$str .= $reserved->seats_numbers;
}
var_dump(array($str));
Or just implode the source array:
var_dump(array(implode('', $this->dashboard_model->get_booked_seats_info($id))));

Related

Store array data in single line PHP

Hello i want to store my array data into variable.
$array = array('0' => "14254",'1' => "145245");
// I want to store this array value into normal single variable
// store array data to $string.
// something like this >> $string is 14254,145245
Use array's implode() method.The implode() function returns a string from the elements of an array.
<?php
$array = array('0' => "14254",'1' => "145245");
$script = implode(',',$array);//outputs 14254,145245
echo $script;
?>
For more see manual PHP Implode
Look at 'serialize' function in PHP. It will provide you array as a string that later could be converted back to array with 'unserialize'

Grouping in PHP using a character

I have an array like:
array{
0 => string 'B.E - ECE',
1 => string 'B.E - EEE',
2 => string 'Msc - Maths',
3 => string 'Msc - Social',
}
So how can I make the array into groups like:
B.E. => ECE, EEE
Msc => Maths,Social
?
I want to do it in PHP. Can anybody help me how to achieve it ?
So is your array split by the "-" character?
so it's Key - Value pairs split by commas?
Ok -
(edit: section removed to clarify answer)
Following conversation and some rearrangement of the question, a second try at a solution, with the above assumptions, try this:
$array = array {
0 => string 'B.E - ECE' (length=9)
1 => string 'B.E - EEE' (length=9)
2 => string 'Msc - Maths' (length=11)
3 => string 'Msc - Social' (length=12)
}
foreach ($array as $row){
$piece = explode("-",$row);
$key = $piece[0];
$newArray[$key][] = $piece[1];
unset($piece);
}
unset($row) ///tidy up
This will output two arrays each of two arrays:
$newArray[Msc] = array("Maths","Social");
$newArray[B.E] = array("ECE","EEE");
What I did was cause the Foreach loop to automatically add onto the array if the key exists with $newArray[$key][] so that the values are automatically collected by key, and the key is defined as the first half of the original array values.
Printing:
To print the result:
foreach($newArray as $key=>$newRow){
/// there are two rows in this case, [B.E] and [MSc]
print $key.":<br>";
print "<pre>";
///<pre> HTML tag makes output use linebreaks and spaces. neater.
print_r($newRow);
///alternatively use var_dump($newRow);
print "</pre>";
}
Alternatively if you wish to print a known named variable you can write:
print_r($newArray['B.E']);
Which will print all the data in that array. print_r is very useful.
what you want is php's explode. Not sure if this will give you the perfect answer but should give you an idea of what to do next.
$groupedArray = array();
foreach($array as $row){
$split = explode(" - ",$row);
$groupedArray[] = $split[0];
}
array_unique($groupedArray); //This will give you the two groupings
foreach($array as $row){
$split = explode(" - ",$row);
$pos = array_search($split[0],$groupedArray);
if($pos !== FALSE){
$groupedArray[$pos][] = $split[1];
}
}
This should give you a full formatted array called $groupedArray where $array is the array you already have.
Hope this helps!

PHP json_encode issue

I have a bunch of values and a PHP array and I need to convert it to a JSON value for posting via CURL to parse.com
The problem is that PHP arrays are converted to JSON objects (string as key and value, vs string as just value)
I end up with
{"showtime":{"Parkne":"1348109940"}}
Rather then
{"showtime":{Parkne:"1348109940"}}
And parse complains that this is a object not an array and therefore won't accept it.
As
{"showtime":{"Parkne":"1348109940"}}
is a JSON object (key = a string)
Is there anyway to do this using json_encode? Or some solution?
That's the JSON spec: Object keys MUST be quoted. While your first unquoted version is valid Javascript, so's the quoted version, and both will parse identically in any Javascript engine. But in JSON, keys MUST be quoted. http://json.org
Followup:
show how you're defining your array, unless your samples above ARE your array. it all comes down to how you define the PHP structure you're encoding.
// plain array with implicit numeric keying
php > $arr = array('hello', 'there');
php > echo json_encode($arr);
["hello","there"] <--- array
// array with string keys, aka 'object' in json/javascript
php > $arr2 = array('hello' => 'there');
php > echo json_encode($arr2);
{"hello":"there"} <-- object
// array with explicit numeric keying
php > $arr3 = array(0 => 'hello', 1 => 'there');
php > echo json_encode($arr3);
["hello","there"] <-- array
// array with mixed implicit/explicit numeric keying
php > $arr4 = array('hello', 1 => 'there');
php > echo json_encode($arr4);
["hello","there"] <-- array
// array with mixed numeric/string keying
php > $arr5 = array('hello' => 'there', 1 => 'foo');
php > echo json_encode($arr5);
{"hello":"there","1":"foo"} <--object
Blind shot... I have the impression that your PHP data structure is not the one you want to begin with. You probably have this:
$data = array(
'showtime' => array(
'Parkne' => '1348109940'
)
);
... and actually need this:
$data = array(
array(
'showtime' => array(
'Parkne' => '1348109940'
)
)
);
Feel free to edit the question and provide a sample of the expected output.
You can convert your array to JSON using json_encode
assuming your array is not empty you can do it like this
$array=();
$json = json_encode($array);
echo $json;
It sounds like you need to take your single object and wrap it in an array.
Try this:
// Generate this however you normally would
$vals = array('showtime' => array("Parkne" => "1348109940"));
$o = array(); // Wrap it up ...
$o[] = $vals; // ... in a regular array
$post_me = json_encode($o);

Creating menu from Text

I am very new to PHP programming and dont know the exact syntax of various labrary functions like , split, find ,etc.
I am having following text with me
in a string variable
$menu = '/home-page|HOME
/our-iphone-app|OUR iPhone APP
/join-us|JOIN ME
/contact-us|CONTACT US';
I want to populate to arrays with this text one array containing the portion before the pipe | and second array contains portions after pipe. How to do this using some split by char(|) method.
Finally arrays must contain
$arraypage = {'0'->'/home-page','1'->'/our-iphone-app'} // etc, and...
$arrayTitle = {'0'->'HOME','2'->'OUR iPhone App'} // etc
You need to break up the string by new lines and then by pipe characters.
$lines = explode("\n", $menu);
$arraypage = array();
$arrayTitle = array();
foreach($lines as $line) {
list($arraypage[], $arrayTitle[]) = explode('|', $line);
}
var_dump of the resulting arrays gives:
array
0 => string '/home-page' (length=10)
1 => string '/our-iphone-app' (length=15)
2 => string '/join-us' (length=8)
3 => string '/contact-us' (length=11)
array
0 => string 'HOME' (length=4)
1 => string 'OUR iPhone APP' (length=14)
2 => string 'JOIN ME' (length=7)
3 => string 'CONTACT US' (length=10)
$array = explode("\n", $array);
$result1 = array();
$resutl2 = array();
foreach($array as $arr){
$temp = explode('|', $arr);
$result1[] = $temp[0];
$result2[] = $temp[1];
}
I'd suggest you make your string contain another separator like so:
$menu = '/home-page|HOME:/our-iphone-app|OUR iPhone APP:/join-us|JOIN ME:/contact-us|CONTACT US';
Then you can use the explode method to split up your string to an associative array.
$array = explode(":", $menu);
foreach($array as $key => $val) {
$array[$key] = explode("|", $val);
}
I'd probably just define the data in an array to start with, rather than as a string. I'd also build it in the format
$menu_array = {
{'url'=>'/home-page','text'=>'HOME'},
{'url'=>'/our-iphone-app','text'=>'OUR iPhone APP'},
{'url'=>'/join-us','text'=>'JOIN ME'},
{'url'=>'/contact-us','text'=>'CONTACT US'},
};
Since that's almost certainly going to be more useful for whatever you do with it next.
If you do need to use a string for some reason though, I'd say a regular expression is the tidiest way to do this. The following:
preg_match_all('/^(?P<url>[^|]+)\\|(?P<text>\\V+)\\v*$/m',$menu,$menu_array,PREG_SET_ORDER)
would set $menu_array to the format I used above.
In fairness, using a regular expression for this may be a little overkill, but I prefer the power of regexes, which are easier to tweak later when you want to add things than loops of explode()s.

Convert this associative array to a string or single indexed array

I need to convert this array into a single dimensional indexed array or a string. Happy to discard the first key (0, 1) and just keep the values.
$security_check_whitelist = array
0 =>
array
'whitelisted_words' => string 'Happy' (length=8)
1 =>
array
'whitelisted_words' => string 'Sad' (length=5)
I tried array_values(), but it returned the exact same array structure.
This works:
$array_walker = 0;
$array_size = count($security_check_whitelist);
while($array_walker <= $array_size)
{
foreach($security_check_whitelist[$array_walker] as $security_check_whitelist_value)
{
$security_check[] = $security_check_whitelist_value;
}
$array_walker++;
}
But it returns:
Warning: Invalid argument supplied for
foreach()
How can I convert the associative array without receiving the warning message? Is there a better way?
foreach ($security_check_whitelist as &$item) {
$item = $item['whitelisted_words'];
}
Or simply:
$security_check_whitelist = array_map('current', $security_check_whitelist);
The problem here could be that you should only walk up to N-1, so $array_walker < $array_size.
So is "whitelisted_words" an array as well? If so, I think the following would work:
$single_dim_array = array();
foreach(array_values($security_check_whitelist) as $item) {
foreach($item['whitelisted_words'] as $word) {
$single_dim_array[] = $word;
}
}
Then the variable $single_dim_array contains all your whitelisted words.

Categories