How To Access Values In Associative Array Using PHP - 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
}

Related

How do I add keys recursively to an array

I have a query result set which I loop through. Depending on the data inside the result set, I want to add it to the array, or if the specific value contains an ID, loop again, and add it at the current position. I want to end up with something like this.
Array
(
[0] => Array
(
[title] => Array
(
[0] => Array
(
[value] => Lorem ipsum
)
)
[uid] => Array
(
[0] => Array
(
[uid] => Array
(
[value] => 1
)
[field_name] => Array
(
[value] => John Doe
)
)
)
)
)
I accomplished the result, but I'm looping over and over again, I would like it to be recursive. So I ended up doing something like this.
foreach ($fields as $nr => $field){
if ($field_type == 'entity_reference'){
// Query again
...
foreach ($fields2 as $nr2 => $field2){
if ($field_type2 == 'entity_reference'){
// Query again
...
} else {
$return[$nr][$field][$nr2][$fieldl2] = $value2;
}
}
} else {
$return[$nr][$field][] = $value;
}
}
How can I make it recursive, so I don't have to loop many times?

Get array sub-element when the array name is unique in php

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

Iterate though a Object and echo values

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

Need help to understand result set from PDO

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/>';
}

How can I create multidimensional arrays from a string in PHP?

So My problem is:
I want to create nested array from string as reference.
My String is "res[0]['links'][0]"
So I want to create array $res['0']['links']['0']
I tried:
$result = "res[0]['links'][0]";
$$result = array("id"=>'1',"class"=>'3');
$result = "res[0]['links'][1]";
$$result = array("id"=>'3',"class"=>'9');
when print_r($res)
I see:
<b>Notice</b>: Undefined variable: res in <b>/home/fanbase/domains/fanbase.sportbase.pl/public_html/index.php</b> on line <b>45</b>
I need to see:
Array
(
[0] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 1
[class] => 3
)
)
)
[1] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 3
[class] => 9
)
)
)
)
Thanks for any help.
So you have a description of an array structure, and something to fill it with. That's doable with something like:
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
// unoptimized, always uses strings
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
array_create( $res, "[0]['links'][0]", array("id"=>'1',"class"=>'3') );
array_create( $res, "[0]['links'][1]", array("id"=>'3',"class"=>'9') );
Note how the array name itself is not part of the structure descriptor. But you could theoretically keep it. Instead call the array_create() function with a $tmp variable, and afterwards extract() it to achieve the desired effect:
array_create($tmp, "res[0][links][0]", array(1,2,3,4,5));
extract($tmp);
Another lazy solution would be to use str_parse after a loop combining the array description with the data array as URL-encoded string.
I have a very stupid way for this, you can try this :-)
Suppose your string is "res[0]['links'][0]" first append $ in this and then put in eval command and it will really rock you. Follow the following example
$tmp = '$'.'res[0]['links'][0]'.'= array()';
eval($tmp);
Now you can use your array $res
100% work around and :-)
`
$res = array();
$res[0]['links'][0] = array("id"=>'1',"class"=>'3');
$res[0]['links'][0] = array("id"=>'3',"class"=>'9');
print_r($res);
but read the comments first and learn about arrays first.
In addition to mario's answer, I used another function from php.net comments, together, to make input array (output from jquery form serializeArray) like this:
[2] => Array
(
[name] => apple[color]
[value] => red
)
[3] => Array
(
[name] => appleSeeds[27][genome]
[value] => 201
)
[4] => Array
(
[name] => appleSeeds[27][age]
[value] => 2 weeks
)
[5] => Array
(
[name] => apple[age]
[value] => 3 weeks
)
[6] => Array
(
[name] => appleSeeds[29][genome]
[value] => 103
)
[7] => Array
(
[name] => appleSeeds[29][age]
[value] => 2.2 weeks
)
into
Array
(
[apple] => Array
(
[color] => red
[age] => 3 weeks
)
[appleSeeds] => Array
(
[27] => Array
(
[genome] => 201
[age] => 2 weeks
)
[29] => Array
(
[genome] => 103
[age] => 2.2 weeks
)
)
)
This allowed to maintain numeric keys, without incremental appending of array_merge. So, I used sequence like this:
function MergeArrays($Arr1, $Arr2) {
foreach($Arr2 as $key => $Value) {
if(array_key_exists($key, $Arr1) && is_array($Value)) {
$Arr1[$key] = MergeArrays($Arr1[$key], $Arr2[$key]);
}
else { $Arr1[$key] = $Value; }
}
return $Arr1;
}
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
$input = $_POST['formData'];
$result = array();
foreach ($input as $k => $v) {
$sub = array();
array_create($sub, $v['name'], $v['value']);
$result = MergeArrays($result, $sub);
}

Categories