parse_str array return only last value - php

I am using ajax to submit the form and ajax value post as:
newcoach=6&newcoach=11&newcoach=12&newcoach=13&newcoach=14
In PHP I am using parse_str to convert string to array,but it return only last value:
$newcoach = "newcoach=6&newcoach=11&newcoach=12&newcoach=13&newcoach=14";
$searcharray = array();
parse_str($newcoach, $searcharray);
print_r($searcharray);
Result array having only last value:
Array
(
[newcoach] => 14
)
Any help will be appreciated...

Since you set your argument newcoach multiple times, parse_str will only return the last one. If you want parse_str to parse your variable as an array you need to supply it in this format with a '[ ]' suffix:
$newcoach = "newcoach[]=6&newcoach[]=11&newcoach[]=12&newcoach[]=13&newcoach[]=14";
Example:
<?php
$newcoach = "newcoach[]=6&newcoach[]=11&newcoach[]h=12&newcoach[]=13&newcoach[]=14";
$searcharray = array();
parse_str($newcoach, $searcharray);
print_r($searcharray);
?>
Outputs:
Array ( [newcoach] => Array ( [0] => 6 [1] => 11 [2] => 12 [3] => 13 [4] => 14 ) )

Currently it is assigning the last value as all parameter have same name.
You can use [] after variable name , it will create newcoach array with all values within it.
$test = "newcoach[]=6&newcoach[]=11&newcoach[]=12&newcoach[]=13&newcoach[]=14";
echo '<pre>';
parse_str($test,$result);
print_r($result);
O/p:
Array
(
[newcoach] => Array
(
[0] => 6
[1] => 11
[2] => 12
[3] => 13
[4] => 14
)
)

Use this function
function proper_parse_str($str) {
# result array
$arr = array();
# split on outer delimiter
$pairs = explode('&', $str);
# loop through each pair
foreach ($pairs as $i) {
# split into name and value
list($name,$value) = explode('=', $i, 2);
# if name already exists
if( isset($arr[$name]) ) {
# stick multiple values into an array
if( is_array($arr[$name]) ) {
$arr[$name][] = $value;
}
else {
$arr[$name] = array($arr[$name], $value);
}
}
# otherwise, simply stick it in a scalar
else {
$arr[$name] = $value;
}
}
# return result array
return $arr;
}
$parsed_array = proper_parse_str($newcoach);

Related

Get id if the text match with array

I need the Id if the 'Final' text match on this array. Like this for array one 288617 and for array two 288031.
Array
(
[0] => a:4:{i:0;s:11:"Demo Course";i:1;s:6:"288616";i:2;s:10:"Final Exam";i:3;s:6:"288617";}
)
Array
(
[0] => a:29:{i:0;s:16:"Sage 50 Accounts";i:1;s:6:"287967";i:2;s:6:"278823";i:3;s:6:"278824";i:4;s:6:"278825";i:5;s:6:"278826";i:6;s:6:"278856";i:7;s:6:"278857";i:8;s:6:"278858";i:9;s:6:"278859";i:10;s:6:"278860";i:11;s:6:"278861";i:12;s:6:"278862";i:13;s:6:"279608";i:14;s:6:"279609";i:15;s:6:"279610";i:16;s:6:"279611";i:17;s:6:"278821";i:18;s:6:"279612";i:19;s:6:"279613";i:20;s:6:"279681";i:21;s:6:"279677";i:22;s:6:"279678";i:23;s:6:"279679";i:24;s:6:"279680";i:25;s:9:"Mock Exam";i:26;s:6:"288030";i:27;s:10:"Final Exam";i:28;s:6:"288031";}
)
I have tried with this code, but can't work.
$search_text = 'Final';
array_filter($array, function($el) use ($search_text) {
return ( strpos($el['text'], $search_text) !== false );
});
First you have to unserialize that text. Then the simplest way is to loop and check for the text and then take the next element:
$array[0] = unserialize($array[0]);
$search_text = 'Final';
foreach($array[0] as $key => $value){
if(strpos($value, $search_text) !== false) {
$result = $array[0][$key+1];
break;
}
}
This assumes that the array is paired the way you have shown:
Array
(
[0] => Demo Course
[1] => 288616
[2] => Final Exam
[3] => 288617
)
With your second array it would only return the first ID 287967 if you search on Sage.
Try end function.
This function return the last element of your array
$array = ['sample1', 'sample2', ... ,'Final';
$search_text = 'Final';
if(end($aray) == $search_text){
// find
}else{
// not found
}

Conversion of an array from one form to another

I have an array.
Array
(
[0] => 1_4
[1] => 1_1
[2] => 1_2
[3] => 2_3
[4] => 2_5
)
I want to convert it to
Array
(
[1] => Array (4,1,2)
[2] => Array (3,5)
)
Can any1 help me in this? The new keys (1 and 2) are the distinct values from 1st part of array before _.
If the underscore will always be the unique split you could explode on underscore and append results to a new array.
$before = ['1_4','1_1','1_2','2_3','2_5'];
$after = [];
foreach ($before as $entry) {
$index = explode('_',$entry);
$after[$index[0]][] = $index[1];
}
return $after;
Quick and dirty...
foreach($array as $value){ // Loop your current array
$arr = substr($value,0); // Get the character before _, 1 or 2
$val = substr($value,2); // Get character after _, 1,2,3,4 or 5
if($arr == 1){ // if 1_, put into first new array
$newArray[0][] = $val;
}else{
$newArray[1][] = $val; // Put into second array else
}
}
print_r($newArray);
Maybe try something like this?
foreach ($array as $element( {
$kv_pair = explode("_", $element, 2);
if (array_key_exists($kv_pair[0])) {
array_push($new_array[$kv_pair[0]], $kv_pair[1]);
} else {
$new_array[$kv_pair[0]] = [$kv_pair[1]];
}
}

Get specific content from a string

I need to get numbers as an array from a given string.
Example string:
$t = '1-P,2-T,3-P,4-R,5-C,6-T,';
Expected output:
if I search -T the output needs to be like this:
array(
[0] => 2,
[1] => 6
)
if it's -P:
array(
[0] => 1,
[1] => 3
)
I tried var_export(explode("-T,",$t)); but it didn't work as expected.
Can any one give me a suggestion to get this?
The below matches the full integer number which preceeds the search term -P.
Let's keep it concise:
$matches = array();
if (preg_match_all('/([0-9]+)\-P/', $t, $matches) >= 1) {
var_dump($matches[1]);
}
Search for '/([0-9]+)\-P/, '/([0-9]+)\-C/, '/([0-9]+)\-T/ an so on.
A more dynamic way to look for different search terms/filters:
$filter = '-T';
$pattern = sprintf('/([0-9]+)%s/', preg_quote($filter));
See preg_match_all and preg_quote functions.
Try this:
$t = '211111111131-P,2-T,3654554-P,4-R,5-C,6-T,';
$find = "-P"; // Search element
$found = []; // Result array
$array = explode(",", $t); // Breaking up into array
foreach($array as $arr) {
if (strpos($arr, $find)) { // Checking if search element is found in $arr
$found[] = explode('-',$arr)[0]; // Extracting the number prefix e.g 1 for 1-P
}
}
Output:
Array
(
[0] => 1
[1] => 3
)
Use it as
$t = '1-P,2-T,3-P,4-R,5-C,6-T,';
$data = explode(",", $t);
print_r($data);
$row=array();
for ($i = 0; $i <= count($data); $i++) {
if (!empty($data[$i])) {
if (strpos($data[$i], '-T') !== false) {// pass find value here
$final = explode("-", $data[$i]);
$row[]=$final[0];
}
}
}
print_r($row);
Output
Array
(
[0] => 2
[1] => 6
)
DEMO
$t = '1-P,2-T,3-P,4-R,5-C,6-T,';
$temp = [];
// if the last comma is not typo the 3rd argument `-1` omit empty item
$array = explode(",", $t, -1);
foreach($array as $arr) {
list($v, $k) = explode('-', $arr);
$temp[$k][] = $v;
}
print_r($temp['T']);
demo
Lots of good answers here already, but none take the approach of first putting the data into a better structure.
The code below converts the data to an associative array mapping letters to arrays of numbers, so that you can then do repeated lookups by whichever letter you want:
$t = '1-P,2-T,3-P,4-R,5-C,6-T,';
$a = array_filter(explode(',', $t));
$map = [];
foreach($a as $item) {
$exploded = explode('-', $item);
$number = $exploded[0];
$letter = $exploded[1];
if (!array_key_exists($letter, $map)) {
$map[$letter] = [];
}
$map[$letter][] = $number;
}
print_r($map);
// Array
// (
// [P] => Array
// (
// [0] => 1
// [1] => 3
// )
//
// [T] => Array
// (
// [0] => 2
// [1] => 6
// )
//
// [R] => Array
// (
// [0] => 4
// )
//
// [C] => Array
// (
// [0] => 5
// )
//
// )
print_r($map['T']);
// Array
// (
// [0] => 2
// [1] => 6
// )
print_r($map['P']);
// Array
// (
// [0] => 1
// [1] => 3
// )

In zend pass values to view by concating array in controller

I have below array where I am getting this array by executing an MySQL query in zend.
I want to concatenate all the octent and get the result as 131.208.0.0 and 141.128.0.0 to pass to view to display.
Array
(
[0] => Array
(
[octet1] => 131
[octet2] => 208
[octet3] => 0
[octet4] => 0
)
[1] => Array
(
[octet1] => 141
[octet2] => 128
[octet3] => 0
[octet4] => 0
)
)
With the below foreach I get all ailments how do i concatenate each octent for an array.
foreach($arr as $external)
{
foreach ($external as $octent)
{
echo $octent."<br />";
}
}
The implode function is what you are searching for:
$results = array();
foreach($arr as $external){
$results[] = implode('.', $external);
}
print_r($results);
If you don't need to work with the individual octets and have access to the query for modification, you could just retrieve CONCAT(octet1, '.', octet2, '.', octet3, '.', octet4) in the SELECT clause.
Otherwise you can just do this :
// array_map applies a function to every element of an array
$concatenated_arr = array_map(function($e) { return implode('.', $e); }, $arr);

weird php array

my php array looks like this:
Array (
[0] => dummy
[1] => stdClass Object (
[aid] => 1
[atitle] => Ameya R. Kadam )
[2] => stdClass Object (
[aid] => 2
[atitle] => Amritpal Singh )
[3] => stdClass Object (
[aid] => 3
[atitle] => Anwar Syed )
[4] => stdClass Object (
[aid] => 4
[atitle] => Aratrika )
) )
now i want to echo the values inside [atitle].
to be specific i want to implode values of atitle into another variable.
how can i make it happen?
With PHP 5.3:
$result = array_map(function($element) { return $element->atitle; }, $array);
if you don't have 5.3 you have to make the anonymous function a regular one and provide the name as string.
Above I missed the part about the empty element, using this approach this could be solved using array_filter:
$array = array_filter($array, function($element) { return is_object($element); });
$result = array_map(function($element) { return $element->atitle; }, $array);
If you are crazy you could write this in one line ...
Your array is declared a bit like this :
(Well, you're probably, in your real case, getting your data from a database or something like that -- but this should be ok, here, to test)
$arr = array(
'dummy',
(object)array('aid' => 1, 'atitle' => 'Ameya R. Kadam'),
(object)array('aid' => 2, 'atitle' => 'Amritpal Singh'),
(object)array('aid' => 3, 'atitle' => 'Anwar Syed'),
(object)array('aid' => 4, 'atitle' => 'Aratrika'),
);
Which means you can extract all the titles to an array, looping over your initial array (excluding the first element, and using the atitle property of each object) :
$titles = array();
$num = count($arr);
for ($i=1 ; $i<$num ; $i++) {
$titles[] = $arr[$i]->atitle;
}
var_dump($titles);
This will get you an array like this one :
array
0 => string 'Ameya R. Kadam' (length=14)
1 => string 'Amritpal Singh' (length=14)
2 => string 'Anwar Syed' (length=10)
3 => string 'Aratrika' (length=8)
And you can now implode all this to a string :
echo implode(', ', $titles);
And you'll get :
Ameya R. Kadam, Amritpal Singh, Anwar Syed, Aratrika
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
echo $item->atitle;
}
}
to get them into an Array you'd just need to do:
$resultArray = array();
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
$resultArray[] = $item->atitle;
}
}
Then resultArray is an array of all the atitles
Then you can output as you'd wish
$output = implode(', ', $resultArray);
What you have there is an object.
You can access [atitle] via
$array[1]->atitle;
If you want to check for the existence of title before output, you could use:
// generates the title string from all found titles
$str = '';
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$str .= $v->title;
}
}
echo $str;
If you wanted these in an array it's just a quick switch of storage methods:
// generates the title string from all found titles
$arr = array();
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$arr[] = $v->title;
}
}
echo implode(', ', $arr);
stdClass requires you to use the pointer notation -> for referencing whereas arrays require you to reference them by index, i.e. [4]. You can reference these like:
$array[0]
$array[1]->aid
$array[1]->atitle
$array[2]->aid
$array[2]->atitle
// etc, etc.
$yourArray = array(); //array from above
$atitleArray = array();
foreach($yourArray as $obj){
if(is_object($obj)){
$atitleArray[] = $obj->aTitle;
}
}
seeing as how not every element of your array is an object, you'll need to check for that.

Categories