weird php array - php

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.

Related

Unset batch of keys in an array from another array elements

I have an array:
$array = Array
(
[0] => qst
[1] => insert_question_note
[2] => preview_ans
[3] => _preview
[4] => view_structure_answer_preview
[5] => index
}
I need to unset the array keys based on elements in
$array_elements_to_be_remove = array('qst','_preview'); // or any string start with '_'
I tried to use:
$array_key = array_search('qst', $array);
unset($array[$array_key]);
$array_key_1 = array_search('_preview', $array);
unset($array[$array_key_1]);
Is there any other better ways to search batch of elements in $array ?
I expect that if I can use array search like this:
$array_keys_to_be_unset = array_search($array_elements_to_be_remove, $array);
I found a way to search the string if it is start with '_' as below:
substr('_thestring', 0, 1)
Any ideas how to do that?
You could use array_filter
$array = Array(
0 => 'qst',
1 => 'insert_question_note',
2 => 'preview_ans',
3 => '_preview',
4 => 'view_structure_answer_preview',
5 => 'index'
);
$array_elements_to_be_remove = array('qst', '_preview'); // or any string start with '_'
$new_array = array_filter($array, function($item)use($array_elements_to_be_remove) {
if (in_array($item, $array_elements_to_be_remove) || $item[0] == '_')
return false; // if value in $array_elements_to_be_remove or any string start with '_'
else
return true;
});
var_dump($new_array);
You can use php build function array_diff:
$arr=array_diff($array1, $array2);
Refer this php docs

Storing value in unknown depth of multidimensional array

I have this exath path saved somewhere:
Array
(
[0] => library
[1] => 1
[2] => book
[3] => 0
[4] => title
[5] => 1
)
I have some array and I want to change the value on this index:
$values[library][1][book][0][title][1] = "new value";
I have no idea, how to do this, because there can be any (unknown) number of dimensions. Any hints?
It makes sense to create a function that does this, so:
function array_path_set(array & $array, array $path, $newValue) {
$aux =& $array;
foreach ($path as $key) {
if (isset($aux[$key])) {
$aux =& $aux[$key];
} else {
return false;
}
}
$aux = $newValue;
return true;
}
$values = array(
'library' => array(
1 => array(
'book' => array(
0 => array(
'title' => array(
1 => 'MAGIC VALUE!',
),
),
),
),
),
);
$path = array('library', 1, 'book', 0, 'title', 1);
$newValue = 'ANOTHER MAGIC VALUE!';
var_dump($values);
var_dump(array_path_set($values, $path, $newValue));
var_dump($values);
Try
foreach ($array as $val) {
$indexes .= "[$val]";
}
${'output'.$indexes} = 'something';
Or
$indexes = '';
foreach ($array as $val) {
$indexes .= "[$val]";
}
$output = 'values'.$indexes;
$$output = 'something';
Are you trying to provide a new value for the title of book 0 in library 1? If so, you will have to search for library "1", with book "0" and then change the value of the "title". So if all your values in the array have the same six entries, start with loc = 0 look at the values at loc+1 (library id), loc+3 (book id) and loc+5 .. change title) .. if not increment loc by 6 and continue searching.
[sounds like homework, so no code provided. Pardon me if I am wrong.]
Just in case you weren't aware of it, the key
$values["library"][1]["book"][0]["title"][1]
Is not the same as the array example in your post. Presuming the array is $values, it has five elements:
$values = Array
(
[0] => "library"
[1] => 1
[2] => "book"
[3] => 0
[4] => "title"
[5] => 1
)
$values[0] = "Library";
$values[1] = "1";
$values[2] = "book";
$values[3] = "0";
etc...
Is this array structure what you intended? If not, post back with a more complete structure so we can help.
Also, you need quotes around the strings - I have included for clarity
You could take a look at the following link for array_search. Some of the posters have included examples of a multidimensional array search and there are other examples. Do a google search on "multidimensional array search" and you will likely find a solution. If you need more direction, post back your details.
try this ->
$keys = array('0'=>'for','1'=>'test','2'=>'only');
$value='ok';
function addArrayPathWithValue($keys,$value,$array = array(),$current =
array())
{
$function = __FUNCTION__;
if (count($current)==0)
{
$keys = array_reverse($keys);
$current = $value;
}
if (count($keys)==0)
{
return $current;
}
$array[array_shift($keys)]=$current;
return $function($keys,$value,NULL,$array);
}
$array = addArrayPathWithValue($keys,$value);
print_r($array);
//output: Array ( [for] => Array ( [test] => Array ( [only] => ok ) ) )

php create multidimensional array from flat one

I have an array like this:
<?php
$array = array( 0 => 'foo', 1 => 'bar', ..., x => 'foobar' );
?>
What is the fastest way to create a multidimensional array out of this, where every value is another level?
So I get:
array (size=1)
'foo' =>
array (size=1)
'bar' =>
...
array (size=1)
'x' =>
array (size=1)
0 => string 'foobar' (length=6)
<?php
$i = count($array)-1;
$lasta = array($array[$i]);
$i--;
while ($i>=0)
{
$a = array();
$a[$array[$i]] = $lasta;
$lasta = $a;
$i--;
}
?>
$a is the output.
What exactly are you trying to do? So many arrays of size 1 seems a bit silly.
you probably want to use foreach loop(s) with a key=>value pair
foreach ($array as $k=>$v) {
print "key: $k value: $v";
}
You could do something like this to achieve the array you asked for:
$newArray = array();
for ($i=count($array)-1; $i>=0; $i--) {
$newArray = array($newArray[$i]=>$newArray);
}
I'm confused about what you want to do with non-numeric keys (ie, x in your example). But in any case using array references will help
$array = array( 0 => 'foo', 1 => 'bar', x => 'foobar' );
$out = array();
$curr = &$out;
foreach ($array as $key => $value) {
$curr[$value] = array();
$curr = &$curr[$value];
}
print( "In: \n" );
print_r($array);
print( "Out : \n" );
print_r($out);
Prints out
In:
Array
(
[0] => foo
[1] => bar
[x] => foobar
)
Out :
Array
(
[foo] => Array
(
[bar] => Array
(
[foobar] => Array
(
)
)
)
)
You can use a recursive function so that you're not iterating through the array each step. Here's such a function I wrote.
function expand_arr($arr)
{
if (empty($arr))
return array();
return array(
array_shift($arr) => expand_arr($arr)
);
}
Your question is a little unclear since in your initial statement you're using the next value in the array as the next step down's key and then at the end of your example you're using the original key as the only key in the next step's key.

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.

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

Categories