I have the following function executing PDO queries:
// removed error handling for presenting here
function getRows($sql) {
$stmt = $this->db->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
}
The result is:
Array
(
[0] => Array
(
[id] => 1
[category] => Audi
)
[1] => Array
(
[id] => 2
[category] => BMW
)
[2] => Array
(
[id] => 3
[category] => Chrysler
)
)
The the following foreach code:
foreach($result as $key => $value ) {
echo $value.'<br/>';
}
outputs this:
Array
Array
Array
What can I do so it returns the following?
Audi
BMW
Chrysler
I understand that I could just do $value['category].
But that's not what I want to achieve / understand. I would like the resultset not to be an array of arrays.
try
foreach($result as $key => $value ) {
echo $value['category'].'<br/>';
}
Alternative
foreach($result as $k)
{
echo $k['category'];
}
The foreach loop splits up your array into key, value pairs. The key in your loop is the index of the array, the value is an array containing ID and Category.
To access the category simply do:
foreach($result as $key => $value ) {
echo $value['category'].'<br/>';
}
Related
I've got two inputs, an ID and multidimensional array
For example, let's say the ID = 5 and the array looks like this:
Array
(
[0] => stdClass Object
(
[year] => 2017
[value] => a:9:{i:5;b:1;i:38;b:1;i:40;b:1;i:42;b:1;i:44;b:1;i:29;b:1;i:46;b:1;i:27;b:1;i:48;b:1;}
)
[1] => stdClass Object
(
[year] => 2018
[value] => a:9:{i:31;b:1;i:5;b:1;i:25;b:1;i:16;b:1;i:27;b:1;i:29;b:1;i:12;b:1;i:14;b:1;i:34;b:1;}
)
[2] => stdClass Object
(
[year] => 2018
[value] => a:3:{i:12;b:1;i:14;b:1;i:16;b:1;}
)
)
I need to unserialize the value and aggregate the data yearly. For example of ID = 5, the output should look like this:
Array
(
[2017] => 1
[2018] => 1
)
Currently I've got so far as to unserialize the value part:
foreach($results as $object=>$result){
echo $result->year;
echo "<br>";
echo join(',', array_keys(unserialize($result->value)));
echo "<br>";
}
Please advise on how to move on from here.
After you unserialize the value, check if the element whose key is ID is set. If it is, increment a counter for the year.
$id = 5;
$output = array();
foreach ($results as $result) {
$value = unserialize($result->value);
if (!empty($value[$id])) {
if (isset($output[$result->year])) {
$output[$result->year]++;
} else {
$output[$result->year] = 1;
}
}
}
print_r($output);
I have this array object:
//$array
Array (
[#insert_long_unique_id] =>
Array (
[0] => WP_Post Object ( [ID] => 770
) )
[#insert_long_unique_id] =>
Array (
[0] => WP_Post Object ( [ID] => 530
) )
The #insert_long_unique_id is an auto-generated ID and I dunno which method or plugin generate it but it's always different.
I need to reach and echo the [ID] => 770 (first-element) only in my project.
You can do it through array_column()
$id_array = array_column($array,'ID');
echo $id_array[0]; //print first-id
//In case if you want to print all ID's
foreach($id_array as $id_arr){
echo $id_arr;
}
If your array variable name is $array, then you can access to ID inside of object like this:
foreach ($array as $key => $value) {
if (!empty($value)) {
if(!empty($value[0]) && is_object($value[0])){
$myid = $value[0]->ID;
}
}
}
i am trying to get all array values of an multidimentional array, but the thing is array can be 1 levels deep or 2, 3 or 4 , i.e. n levels deep.
here are some random e.g. of array contents.
e.g.1
Array
(
[0] => Array
(
[0] => name0
)
[1] => Array
(
[0] => name1
)
[2] => Array
(
[0] => name2
)
[3] => Array
(
[0] => name3
)
[4] => Array
(
[0] => name4
)
[5] => Array
(
[0] => name4
)
[6] => Array
(
[0] => name5
)
)
e.g.2
Array
(
[0] => Array
(
[0] => name0
[1] => name1
[2] => name2
[3] => name3
[4] => name4
[5] => name5
)
)
I want all values to be in new array.
So far i have tried something like this.
looping for n times using foreach loop, its working fine for now, but i would like to know if its programmatically correct or is there any other way which is faster or better than this one.
PHP CODE.
<?php
$out_final_array = array ();
function foreach_values_endless($array){
global $out_final_array;
/* if its array */
if(is_array($array)){
/*run foreach loop to find more sub arrays */
foreach ($array as $value){
/* if value is an array send to own custom function */
if(is_array($value)){
$out_final_array[] = foreach_values_endless(array_values($value));
}else{
/* value is not an array*/
$out_final_array[] = $value;
}
}
}else{
/* value is not array */
$out_final_array[] = $array;
}
}
If you need to flatten it, another way would be to use SPL RecursiveArrayIterator and RecursiveIteratorIterator:
$new_data = array();
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
foreach($it as $v) {
$new_data[] = $v;
}
Sample Output
Sidenote: No need for that global just have it return the values:
function foreach_values_endless($array){
$data = array();
foreach ($array as $k => $v) {
if (is_array($v)) {
$data = array_merge($data, foreach_values_endless($v));
} else {
$data[] = $v;
}
}
return $data;
}
Sample Output
You can use array_walk_recursuve():
$final = array();
array_walk_recursive($input, function($item, $key) use (&$final){
$final[0][] = $item;
});
This should work for you:
Just loop through all of your values with array_walk_recursive(), like this:
$result = [];
array_walk_recursive($arr, function($v, $k)use(&$result){
$result[] = $v;
});
print_r($result);
I tried a lot of different methods. I managed to get the first part working but the second part to get the fruits name isn't working.
I have an object stored in $food, the print_r() output of this object is shown below:
Food Object
(
[id] => 1
[values] => Array
(
[name] => Myfood
)
[objects] => Array
(
[0] => Fruits Object
(
[id] => 1
[values] => Array
(
[name] => My Fruits
)
[objects] => Array
(
[0] => FruitType Object
(
[id] => 1
[values] => Array
(
[name] => Orange1
)
)
)
)
)
)
This code displays 'Myfood' successfully:
foreach ($food->values as $key => $value) {
echo "$key => $value";
}
This code displays 'My fruits' successfully:
echo '<br/>';
foreach ($food->objects as $id => $owner) {
foreach ($owner->values as $key => $value) {
echo "$key => $value";
}
}
I need a second block of code that displays the FruitType object values Orange1, I tried a few things but didn't work out well.
It looks as if you've run into the greatest stumbling block all developers face... naming things. I've probably not done too much better as I'm not 100% sure what your end goal is but you were on the right track as far as nesting loops is concerned.
foreach ($food->objects as $i => $obj) {
echo "name => {$obj->values['name']}\n";
foreach ($obj->objects as $j => $type) {
foreach($type->values as $key => $val){
echo " $key => $val\n";
}
}
}
Working Example
Looking at the structure of your object though - recursive iteration may be more readable.
Why don't you just use the get_object_vars() function ?
see more here : http://php.net/manual/fr/function.get-object-vars.php
I have an array which is the result of a select query using Amazon SimpleDb.
Here is sample data when I print_r($result);
Array ( [0] => Array ( [Name] => 5140ede647e74
[Attributes] => Array (
[0] => Array ( [Name] => test_id [Value] => 5140ede647e74 )
[1] => Array ( [Name] => test_name [Value] => test1 )
[2] => Array ( [Name] => last_update [Value] => 1363209702 )
[3] => Array ( [Name] => created [Value] => 1363209702 ) ) ) )
If I want to extract the test_id and the test_name, how can I do it? I am currently doing the following
<?php foreach ($result as $item) {
echo $item['Attributes'][0]['Value'];
echo $item['Attributes'][1]['Value'];
} ?>
But I want to do it by referencing "test_id" and "test_name" because when I delete the domain where the data resides and re-enter the data, the order of each attribute can change so I can't trust that $item['Attributes'][0]['Value'] will always be the test_id
Thanks!
foreach ($result as $item) {
foreach ($item['Attributes'] as $keyvalue) {
if ($keyvalue['Name'] == 'test_id' || $keyvalue['Name'] == 'test_name') {
echo $keyvalue['Value'];
}
}
}
You need to recast the Array.
$newArray = array();
foreach ($result as $key=>$row)
{
foreach ($row['Attributes'] AS $row2)
{
$newArray[$key][$row2['Name']] = $row2['Value'];
}
}
EDIT: It depends on what you need to do - this is my preferred method if I plan on doing a lot of work with a resultset - I only need to iterate through the set once and then it's in a format where the data can be accessed quickly.
The following will run trough the last part of your array by reference. Therefore edits that you make are reflected in the $result array.
foreach ($result[0]['Attributes'] as &$item) {
if ($item['Name'] == 'test_id') // do something
}