In zend pass values to view by concating array in controller - php

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);

Related

parse_str array return only last value

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);

PHP: How can I get the value from a key in a multiple array

The multiple array looks like
Array
(
[id] => description
[header] =>
[width] => 20
[dbfield] => description
[type] => text
)
Array
(
[id] => quantity
[header] => Menge
[dbfield] => QUANTITY_NEW
[width] => 60
[type] => decimal
)
How can I get the value from dbfield where id is 'quantity' without knowing the numeric value of the id?
The actual code looks like
foreach($array as $id => $fieldData) {
if($fieldData['type'] == 'decimal')
{
doSomething...();
}
}
In the part with doSomething I need access to other fields from the array, but I only know the id. I already tried it with dbfield['quantity']['dbfield'] etc. which obviously fails.
A simple alternative using array_keys:
function getValues($data, $lookForValue, $column)
{
$res = array();
foreach ($data as $key => $data)
{
if($idx = array_keys($data, $lookForValue))
{
$res[$idx[0]] = $data[$column];
}
}
return $res;
}
$values = getValues($myData, "quantity", "dbfield");
var_dump($values);
echo out the array as such..
$array = array();
$array['qty'] = 'qtty';
$array['dbfield'] = 'QUANTITY_NEW';
if($array['qty'] = 'qtty'){
echo $array['dbfield'];
}
returns - QUANTITY_NEW
You can do this with several methods, one of them is using array_map to get those values:
$dbfield = array_filter(array_map(function($a){
if($a["id"] === "quantity"){
return $a["dbfield"];
}
}, $array));
print_r($dbfield);
You iterate over the array, and return the key dbfield where id is 'quantity'. Array filter is just to not return null values where it doesn't have 'quantity' id.
Online attempt to reproduce your code can be found here

Delete array value containing given text

I have this array:
$array = array(
[0] => "obm=SOME_TEXT",
[1] => "sbm=SOME_TEXT",
[2] => "obm=SOME_TEXT"
);
How can I remove array's element(s) containing value obm or sbm (which is always at the top of the string in the array) and update indexes?
Example 1:
print_r(arrRemove("smb", $array));
Output:
$array = array(
[0] => "obm=SOME_TEXT",
[1] => "obm=SOME_TEXT"
);
Example 2:
print_r(arrRemove("omb", $array));
Output:
$array = array(
[0] => "sbm=SOME_TEXT"
);
You can simply loop through the array using a foreach and then use strpos() to check if the array contains the given input string, and array_values() to update the indexes:
function arrRemove($str, $input) {
foreach ($input as $key => $value) {
// get the word before '='
list($word, $text) = explode('=', $value);
// check if the word contains your searchterm
if (strpos($word, $str) !== FALSE) {
unset($input[$key]);
}
}
return array_values($input);
}
Usage:
print_r(arrRemove('obm', $array));
print_r(arrRemove('sbm', $array));
Output:
Array
(
[0] => sbm=SOME_TEXT
)
Array
(
[0] => obm=SOME_TEXT
[1] => obm=SOME_TEXT
)
Demo!
Maybe something like this?
$newarray = array_values(array_filter($oldarray, function($value){
return strpos($value, 'obm') !== 0;
}
));
This is handled by PHP
php.net/manual/en/function.array-pop.php
array_pop() pops and returns the last value of the array , shortening the array by one element.

PHP foreach assigning of array

I'm trying to read recursively into an array until I'm getting a string. Then I try to explode it and return the newly created array. However, for some reason it does not assign the array:
function go_in($arr) { // $arr is a multi-dimensional array
if (is_array($arr))
foreach($arr as & $a)
$a = go_in($a);
else
return explode("\n", $arr);
}
EDIT:
Here's the array definition as printed by print_r:
Array
(
[products] => Array
(
[name] => Arduino Nano Version 3.0 mit ATMEGA328P
[id] => 10005
)
[listings] => Array
(
[category] =>
[title] => This is the first line
This is the second line
[subtitle] => This is the first subtitle
This is the second subtitle
[price] => 24.95
[quantity] =>
[stock] =>
[shipping_method] => Slow and cheap
[condition] => New
[defects] =>
)
[table_count] => 2
[tables] => Array
(
[0] => products
[1] => listings
)
)
I'd use this:
array_walk_recursive($array,function(&$value,$key){
$value = explode("\n",$value);
});
However, this fixes your function:
function &go_in(&$arr) { // $arr is a multi-dimensional array
if (is_array($arr)){
foreach($arr as & $a) $a = go_in($a);
} else {
$arr = explode("\n", $arr);
}
return $arr;
}
When writing nested conditions/loops - always add braces for better readability and to prevent bugs.. Also you should return the go_in function, because it is recursive, it needs to be passed to the calling function instance.
function go_in($arr) { // $arr is a multi-dimensional array
if (is_array($arr))
{
foreach($arr as &$a)
{
return go_in($a);
}
}
else
{
return ($arr);
}
}
The original array was not returned in the function:
function go_in($arr) {
if (is_array($arr))
foreach($arr as &$a)
$a = go_in($a);
else
if (strpos($arr, "\n") !== false)
return explode("\n", $arr);
return $arr;
}
EDIT:
Now, it only really edits the strings that contain a linebreak. Before it would edit every string which meant that every string was returned as an array.

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