how do i access these array keys as a variable in CI? - php

Array
(
[abc] => Array
(
[0] => Array
(
[id] => 1
[title] => hello 12
[meta_keyword] =>
[meta_description] =>
[tags] => sdfgdfg
[status] => draft
[body] => dsfdsf dfdsafsdfsdfsdf
[photo] => images/blog/nari.jpg
[raw] => nari
[ext] => .jpg
[views] => 0
[video] =>
[categoryid] => 5
[subcatid] => 7
[featured] =>
[pubdate] => 2011-06-17 03:39:55
[user_id] => 0
)
[1] => Array
(
[id] => 2
[title] => hello xyz
[meta_keyword] =>
[meta_description] =>
[tags] => xcfasdfcasd
[status] => draft
[body] => dfdsafsdf dsfdsf dfdsafsdfsdfsdf
[photo] => images/blog/nari.jpg
[raw] => nari
[ext] => .jpg
[views] => 0
[video] =>
[categoryid] => 1
[subcatid] => 2
[featured] =>
[pubdate] => 2011-06-17 03:43:12
[user_id] => 0
)
for example if i want to echo out title I would do echo $abc['title'] but it's not working pls help,
the above output is a result of print_r($count['abc]);
it shows nothing when i do print_r($count['abc']['title'])

You would need to use the numeric key as well: $abc[0]['title'].
In other words, you've got an array with array members of an array type which use numeric keys, in which each of those members are arrays which use associative keys to access values. So you need to access each array in $abc to get to the array which contains your title values.
EDIT
If you're trying to loop through these values, you would need to loop through each array. Such as:
$c_abc = count($abc);
for ($i = 0; $i < $c_abc; $i++) {
echo "{$abc[$i]['title']}<br/>";
}

Read about php associative arrays....you will have you goal achieved
try this:
foreach ($array as $i => $values) {
print "$i {\n";
foreach ($values as $key => $value) {
print " $key => $value\n";
}
print "}\n";
}

To access you array variables, the right way is like this
$count['abc'][0]['title']
However, in your title, you are asking about Array keys as variables?
Actually this does not need to be related with CI.
A simple example
$array = array ( "hi" => "bye");
extract( $array);
//it will make "hi" a variable :: $hi = "bye"
echo $hi; // will output bye

Heres structured solution
$data = Array(
[abc] => Array
(
[0] => Array
(
[id] => 1
[title] => hello 12
[meta_keyword] =>
[meta_description] =>
[tags] => sdfgdfg
[status] => draft
[body] => dsfdsf dfdsafsdfsdfsdf
[photo] => images/blog/nari.jpg
[raw] => nari
[ext] => .jpg
[views] => 0
[video] =>
[categoryid] => 5
[subcatid] => 7
[featured] =>
[pubdate] => 2011-06-17 03:39:55
[user_id] => 0
)
[1] => Array
(
[id] => 2
[title] => hello xyz
[meta_keyword] =>
[meta_description] =>
[tags] => xcfasdfcasd
[status] => draft
[body] => dfdsafsdf dsfdsf dfdsafsdfsdfsdf
[photo] => images/blog/nari.jpg
[raw] => nari
[ext] => .jpg
[views] => 0
[video] =>
[categoryid] => 1
[subcatid] => 2
[featured] =>
[pubdate] => 2011-06-17 03:43:12
[user_id] => 0
)
)
);
extract($data);
foreach($abc as $value){
echo $value['title']."<br>";
}

Related

Move a child array to parent array and change parent/child name

I know probably this was asked before not sure if was in this form but I did tried some replay from what I found here about this and failed.
ok I have this array
Array
(
[0] => Array
(
[Data3] => Array
(
[id] => 5
[category] => Whiskey
[name] => Some name
[description] => description
[image] => asdf.jpg
[price] => 83.99
)
[ammount] => 1
[Data_id] => 3
)
[1] => Array
(
[Data3] => Array
(
[id] => 4
[category] => Tequila
[name] => Something Red 75cl
[description] => description
[image] => sierratequilasilver100.jpg
[price] => 92.49
)
[ammount] => 2
[Data_id] => 3
)
[2] => Array
(
[Data4] => Array
(
[id] => 3
[category] => Whiskey
[name] => Some name Gold
[description] => description
[image] => asdf.jpg
[price] => 83.99
)
[ammount] => 1
[Data_id] => 4
)
[3] => Array
(
[Data4] => Array
(
[id] => 5
[category] => Vodka
[name] => Something Blue 100 cl
[description] => description
[image] => Something.jpg
[price] => 32.44
)
[ammount] => 1
[Data_id] => 4
)
)
What I would like to be the result is something like this:
Array
(
[0] => Array
(
[id] => 5
[category] => Whiskey
[name] => Some name
[description] => description
[image] => asdf.jpg
[price] => 83.99
[ammount] => 1
[Data_id] => 3
)
[1] => Array
(
[id] => 4
[category] => Tequila
[name] => Something Red 75cl
[description] => description
[image] => sierratequilasilver100.jpg
[price] => 92.49
[ammount] => 2
[Data_id] => 3
)
[2] => Array
(
[id] => 3
[category] => Whiskey
[name] => Some name Gold
[description] => description
[image] => asdf.jpg
[price] => 83.99
[ammount] => 1
[Data_id] => 4
)
[3] => Array
(
[id] => 5
[category] => Vodka
[name] => Something Blue 100 cl
[description] => description
[image] => Something.jpg
[price] => 32.44
[ammount] => 1
[Data_id] => 4
)
)
or another way I could work with is if I can change Data1, Data2, Data3 and so on ..
can be n Data depends how many producs a user select
into a same name ex simple Data or Info.
ex:
Array
(
[0] => Array
(
[Info] => Array
(
[id] => 5
[category] => Whiskey
[name] => Some name
[description] => description
[image] => asdf.jpg
[price] => 83.99
)
[ammount] => 1
[Data_id] => 3
)
[1] => Array
(
[Info] => Array
(
[id] => 4
[category] => Tequila
[name] => Something Red 75cl
[description] => description
[image] => sierratequilasilver100.jpg
[price] => 92.49
)
[ammount] => 2
[Data_id] => 3
)
Any solution will be fine for me.
Thanks and regards
Use this code for your result:
$final_array = array();
foreach($array1 as $offset1 => $array2) {
$tmp_array = array();
foreach($array2 as $offset2 => $array3) {
if(is_array($array3)) {
$tmp_array = $array3;
} else {
$tmp_array[$offset2] = $array3
}
}
$final_array = array_merge($final_array, $tmp_array;);
//or
$final_array[] = $tmp_array;
}
I would do this this way. However I would look to fix why the data is in that structure to begin with.
$aStartArray = array(array('Data3'=>array('id'=>1, 'cat'=>2), 'amount' => 1, 'Data_id'=>3));
foreach ($aStartArray as $iPos => $aArray) {
$aKeys = array_keys($aArray); // fetches all the keys
$aFirstElement = $aArray[$aKeys[0]]; // Get the first element using first key
// assign/ overwrite data at the same position
$aStartArray[$iPos] = array($aFirstElement, 'amount' => $aArray['amount'], 'Data_id' => $aArray['Data_id']);
}
echo "<pre>";
var_dump($aStartArray);
your first option:
foreach($arr as $key => $value){
foreach($value as $k => $val){
if(is_array($val)){
$arr[$key] = $val;
unset($arr[$key][$k]);
}
}
}
echo "<pre>"; print_r($arr);
Check output here
This is the best algorithm
const moveArrayToParentArray = (input) => {
let finalOutput = []
input.forEach((e) => {
if (Array.isArray(e)) {
finalOutput = [...finalOutput, ...e];
} else {
finalOutput = [...finalOutput, e];
}
})
return finalOutput
}
const array = ['a', 'b']
const array2 = [array]
const array3 = [array, "c"]
console.log(moveArrayToParentArray(array))
console.log("----------------------------")
console.log(moveArrayToParentArray(array2))
console.log("----------------------------")
console.log(moveArrayToParentArray(array3))
console.log("----------------------------")

Looping through associative array using foreach

So I'm using curl to return some JSON from an API and I'm using json_decode($result,true);
I have managed to access the title but I need to loop through the whole array and output the title, url, location and picture.
I'm doing a foreach to print all the content:
<?php
foreach ($json as $value) {
echo "<pre>";
print_r($json);
echo $json['data'][2]['title'];
}
?>
What blocks me its how do I access every element.
Array
(
[paging] => Array
(
[total_items] => 33
[current_page] => 1
[total_pages] => 3
)
[data] => Array
(
[0] => Array
(
[id] => 776583
[title] => NAME
[url] =>URL
[status] => open
[current_status] => open
[location] => a, a
[programmes] => Array
(
[id] => 2
[short_name] => SHORT NAME
)
[applications_count] => 5
[is_favourited] =>
[branch] => Array
(
[id] => 319532
[name] => International SOS - 1
[organisation_id] => 318911
[profile_photo_url] => URL
[url] => URL
)
[views] => 248
[duration_min] => 22
[duration_max] => 24
[applications_close_date] => 2016-09-06T00:00:00.000Z
[earliest_start_date] => 2016-10-01T00:00:00.000Z
[latest_end_date] => 2017-04-01T00:00:00.000Z
[profile_photo_urls] => Array
(
[original] => PIC URL
[medium] => PIC URL
[thumb] => PIC URL
)
[cover_photo_urls] => PNG IMG
[created_at] => 2016-08-30T03:24:41Z
[updated_at] => 2016-08-30T15:36:02Z
)
[1] => Array
(
[id] => 774984
[title] => NAME
[url] => URL
[status] => open
[current_status] => open
[location] => Bonn, Germany
[programmes] => Array
(
[id] => 2
[short_name] => NAME
)
[applications_count] => 128
[is_favourited] =>
[branch] => Array
(
[id] => 287321
[name] => Deutsche Post DHL Group
[organisation_id] => 286836
[profile_photo_url] => PHOTO
[url] => URL
)
[views] => 1331
[duration_min] => 48
[duration_max] => 48
[applications_close_date] => 2016-09-04T00:00:00.000Z
[earliest_start_date] => 2016-10-01T00:00:00.000Z
[latest_end_date] => 2017-10-01T00:00:00.000Z
[profile_photo_urls] => Array
(
[original] => PIC
[medium] => PIC
[thumb] => PIC
)
[cover_photo_urls] => PIC
[created_at] => 2016-08-23T19:47:04Z
[updated_at] => 2016-08-24T06:35:58Z
)
<?php
foreach ($json as $value) {
foreach($value['data'] as $inner){ //looping json['data']
echo $inner['id'];
echo $inner['title'];
foreach($inner['programmes'] as $in_inner){ //looping json['data']['element_number']['programmers']
echo $in_inner['id'].':'.$in_inner['short_name'];
}
}
}
?>
In this way you can iterate through inner arrays.

php error accessing double layer array

My data is in a second tier of a return value that I am trying to access the individual elements. Array ( [success] => 1 [return] => Array ( [0] => Array
I tried ['return'] since it is the key of that, is what I need but got the same error or obvious worse.
error:
Array to string conversion in orders.php on line 10
code:
<?php
$id = $argv[1]; //variable for inbound
require_once('phpPlay.php');
$result = api_query("mytrades", array("marketid" => $id));
foreach( $result as $x) {
echo $x;
}
?>
data top 5 rows:
Array
(
[success] => 1
[return] => Array
(
[0] => Array
(
[tradeid] => 74038377
[tradetype] => Sell
[datetime] => 2014-11-12 16:05:32
[tradeprice] => 0.00675000
[quantity] => 22.18670000
[fee] => -0.00007488
[total] => 0.14976023
[initiate_ordertype] => Buy
[order_id] => 197009493
)
[1] => Array
(
[tradeid] => 73687280
[tradetype] => Buy
[datetime] => 2014-11-09 03:38:13
[tradeprice] => 0.00816988
[quantity] => 0.00100000
[fee] => 0.00000002
[total] => 0.00000817
[initiate_ordertype] => Buy
[order_id] => 194824864
)
[2] => Array
(
[tradeid] => 73684313
[tradetype] => Sell
[datetime] => 2014-11-09 02:57:41
[tradeprice] => 0.00808034
[quantity] => 0.00100000
[fee] => 0.00000000
[total] => 0.00000808
[initiate_ordertype] => Buy
[order_id] => 194803992
)
[3] => Array
(
[tradeid] => 73653019
[tradetype] => Sell
[datetime] => 2014-11-08 17:53:12
[tradeprice] => 0.00793991
[quantity] => 0.00010000
[fee] => 0.00000000
[total] => 0.00000079
[initiate_ordertype] => Buy
[order_id] => 194559503
)
[4] => Array
(
[tradeid] => 73652717
[tradetype] => Sell
[datetime] => 2014-11-08 17:50:13
[tradeprice] => 0.00793989
[quantity] => 0.00100000
[fee] => 0.00000002
[total] => 0.00000794
[initiate_ordertype] => Sell
[order_id] => 194559596
)
...
The problem is that with the echo $x statement in your code above, $x is an array, not a string.
The echo function requires a string, so the error you're getting is because PHP is automatically trying to convert the parameter passed to echo to a string, but it is failing because you are passing an array.
Try this:
if (isset($result['return'])) {
foreach($result['return'] as $result_item) {
echo(var_export($result_item, true));
}
} else {
echo 'No results';
}

PHP: Displaying single array data?

So the code is
$gallery = get_gallery('gallery_id');
print_r ($gallery);
And I get:
Array ( [0] => Array ( [id] => 13 [image] => 0 [user] => 13 [timestamp] => 1366237591 [ext] => png [caption] => Happy smile shi ma? [comment] => ) [1] => Array ( [id] => 14 [image] => 0 [user] => 13 [timestamp] => 1366237954 [ext] => jpg [caption] => Confused [comment] => ) [2] => Array ( [id] => 15 [image] => 0 [user] => 13 [timestamp] => 1366237979 [ext] => jpg [caption] => Facebookerg [comment] => ) [3] => Array ( [id] => 16 [image] => 0 [user] => 13 [timestamp] => 1366377510 [ext] => gif [caption] => lolwut? [comment] => ) [4] => Array ( [id] => 17 [image] => 0 [user] => 13 [timestamp] => 1366380899 [ext] => jpg [caption] => rorwut? [comment] => ) [5] => Array ( [id] => 18 [image] => 0 [user] => 13 [timestamp] => 1366651685 [ext] => jpg [caption] => Notes? [comment] => ) [6] => Array ( [id] => 19 [image] => 0 [user] => 13 [timestamp] => 1366711880 [ext] => jpg [caption] => asd [comment] => ) [7] => Array ( [id] => 20 [image] => 0 [user] => 14 [timestamp] => 1366940983 [ext] => jpg [caption] => Belzelga [comment] => ) )
Which is good, it finally worked. But how do you display a single data/table.
Because I am trying to get a single 'id' from these thingies.
I tried echoing $gallery['id']
but I got an error. :/
You need to access the correct index first:
$gallery[0]['id']
// ^^^
Your $gallery variable is now a multi dimentional array.
You have
$gallery[0]['id'];
$gallery[1]['id'];
.....
Now you can either use a foreach to process through the array or a for loop
foreach ($gallery as $anItem ) {
echo $anItem['id'];
}
OR
for ( $x=0; $x < count($gallery); $x++ ) {
echo $gallery[$x]['id'];
}
Try this looping code-segment:
foreach( $gallery as $temp ) {
echo $temp['id'];
}
Your $gallery is a multidimensional array. You need to iterate through it.
If you want to only display a particular gallery, you should probably use something like www.yoursite.com/gallery.php?id=1. then in your code to display it
if(isset($_GET['id']))
{
foreach( $gallery as $g )
{
if($g['id'] == $_GET['id'])
echo $g['id'];
}
}
You can get the data so. Without being bound to a key.
current($gallery)['id']

Accessing field value in Drupal 7 on load_node in template

In a template for a content type I am loading a node from a node reference.
It loads and if I do a print_r I get this:
stdClass Object (
[vid] => 40
[uid] => 14
[title] => Cover
[log] =>
[status] => 1
[comment] => 0
[promote] => 1
[sticky] => 0
[nid] => 40
[type] => portfolio_image_main
[language] => en
[created] => 1309382711
[changed] => 1309382711
[tnid] => 0
[translate] => 0
[revision_timestamp] => 1309382711
[revision_uid] => 14
[field_portolio_image] => Array (
[en] => Array (
[0] => Array (
[fid] => 5626
[alt] =>
[title] =>
[uid] => 14
[filename] => Cover.jpg
[uri] => public://Cover.jpg
[filemime] => image/jpeg
[filesize] => 147898
[status] => 1
[timestamp] => 1309382711
)
)
)
[name] => jojo
[picture] => 0
[data] => a:1:{s:7:"contact";i:1;}
)
and Im trying to access the single variable here:
$newImagePath1 = $newImage1->field_portfolio_image['en '][0]['filename'];
but so far nothing. Any thoughts?
please try to use below code
$keys = array_keys($arr[field_portolio_image][en]);
$arr[field_portolio_image][en][$keys][filename];
There is a helper function to access field items for the user's correct language (otherwise, you'd have to hardcode the ['en'] part).
field_get_items()
So your code would end up being something like this:
$field_instances = field_get_info('node', $newImage1, 'field_portfolio_image');
// $field_instances should now be an array.
foreach ($field_instances as $field_instance) {
print $field_instance['filepath'];
}

Categories