I have this 3 and 4 multidimensionnal array ($response) which I need to "extract" some values.
Array (
[status] => 200
[response] => Array (
[api_id] => 38229dd9-8c52-11e5-80f6-22000afd0039
[meta] => Array (
[limit] => 20
[next] => /v1/Account/xxx/Call/?limit=20&offset=20
[offset] => 0
[previous] =>
[total_count] => 57 )
[objects] => Array (
[0] => Array (
[answer_time] => 2015-11-13 18:36:19+01:00
[bill_duration] => 10
[billed_duration] => 60
[call_direction] => inbound
[call_duration] => 10
[call_uuid] => dcd94e59-8775-4c81-a4b1-cd5d41d630c6
[end_time] => 2015-11-13 18:36:29+01:00
[from_number] => 3300000000
[initiation_time] => 2015-11-13 18:36:18+01:00
[parent_call_uuid] =>
[resource_uri] => /v1/Account/xxx/Call/dcd94e59-8775-4c81-a4b1-cd5d41d630c6/
[to_number] => 3300000000
[total_amount] => 0.00500
[total_rate] => 0.00500 )
[1] => Array (
[answer_time] => 2015-11-13 15:52:01+01:00 [
bill_duration] => 48
[billed_duration] => 60
[call_direction] => inbound
[call_duration] => 48
[call_uuid] => b2d3de5d-a047-4409-9f7a-825373c38f0a
[end_time] => 2015-11-13 15:52:48+01:00
[from_number] => 3300000000
[initiation_time] => 2015-11-13 15:52:00+01:00
[parent_call_uuid] =>
[resource_uri] => /v1/Account/xxx/Call/b2d3de5d-a047-4409-9f7a-825373c38f0a/
[to_number] => 3300000000
[total_amount] => 0.00500
[total_rate] => 0.00500 )
...
In the [meta] array, I need the [total_count] value and for the [object] array, I'd like to get all the values to disaply them in a row (each object is a new row).
I have tried foreach within foreach or access datas with $response[0][0][0] but nothing do.
If someone could lead me to the solution...
Thanks a lot !!
You can access the meta array through $response['response']['meta']. As you can see from your array, both response and meta are keys, and so is total_count. Hence, accessing total count is done by $response['response']['meta']['total_count'].
To then loop through all your objects, simply do
foreach ($response['response']['objects'] as $object) {
print_r($object);
}
You can also access every attribute of the object individually by using the array keys:
foreach ($response['response']['objects'] as $object) {
echo $object['answer_time'];
echo $object['bill_duration'];
echo $object['billed_duration'];
echo $object['call_direction'];
echo $object['call_duration'];
echo $object['call_uuid'];
echo $object['end_time'];
echo $object['from_number'];
echo $object['initiation_time'];
echo $object['parent_call_uuid'];
echo $object['resource_uri'];
echo $object['to_number'];
echo $object['total_amount'];
echo $object['total_rate'];
}
First, to verify, if $array is the name of your array:
$response = $array["response"];
In the [meta] array, I need the [total_count] value
echo $response["meta"]["total_count"];
and for the [object] array, I'd like to get all the values to disaply them in a row (each object is a new row).
Use a foreach() function for all the objects:
foreach($response["objects"] as $object){
print_r($object);
}
You can use the "count" function with "COUNT_RECURSIVE" flag. It counts all the items inside the 'mixed' var. It counts parent element too.
count($array['objects'],COUNT_RECURSIVE);
example
$cibo = array(
'frutta' => array('arancia', 'banana', 'mela'),
'verdura' => array('carota', 'zucchina', 'piselli')
);
echo count($cibo,COUNT_RECURSIVE); // output 8
Related
I have here an array below:
<?php
print_r( $result );
?>
If I am going to execute the code above, it resulted below:
Array
(
[0] => Array
(
[id] => 1
[uploaded_by] => 1
[image_url] => http://localhost/dir/img_2.jpg
[work_description] => test
[date_added] => 2017-08-03 02:12:38
)
[1] => Array
(
[id] => 2
[uploaded_by] => 1
[image_url] => http://localhost/dir/img_4.jpg
[work_description] => test
[date_added] => 2017-08-03 02:13:04
)
[2] => Array
(
[id] => 3
[uploaded_by] => 1
[image_url] => http://localhost/dir/img_2.jpg
[work_description] => test
[date_added] => 2017-08-03 02:46:28
)
[3] => Array
(
[id] => 4
[uploaded_by] => 1
[image_url] => http://localhost/dir/img_2.jpg
[work_description] => sdfsdf
[date_added] => 2017-08-03 02:46:34
)
)
Now, from the $result array I wanted to change the values of all image_url
programmatically using php into an image in html.
example:
http://localhost/dir/img_2.jpg will become
<img src="http://localhost/dir/img_2.jpg"/>
Those values must be changed if I am going to execute the code.
Does anybody know?
You can put it in a foreach and modify only the part what you want:
foreach($result as $key => $value) {
$result[$key]['image_url'] = '<img src="'.$value['image_url'].'"/>';
}
print_r($result);
You can use a compact syntax and modify the subarray elements by reference:
Code: (Demo)
foreach ($result as &$subarray) { // & means modify by reference, so you are overwriting the input array, not traversing a copy.
$subarray['image_url'] = "<img src=\"{$subarray['image_url']}\"/>";
}
var_export($result);
There is no need to declare $key because the foreach is traversing the actual input array, not a copy of the input array. The image_urls are simply overwritten with each iteration.
I have an array and I'm willing to find a value of a specific key in case another key's value is X.
My array has several other arrays with the following structure:
[3] => Array
(
[ŠIFRA VALUTE] => 156
[NAZIV ZEMLJE] => Kina
[OZNAKA VALUTE] => CNY
[VAŽI ZA] => 1
[SREDNJI KURS] => 16.8711
)
I'm willing to find in the main array, all the values of SREDNJI KURS only if the value of OZNAKA VALUTE is "CNY".
As far as I understood from your question:
var_dump($data);
/*
[0] => Array
(
[ŠIFRA VALUTE] => 156
[NAZIV ZEMLJE] => Kina
[OZNAKA VALUTE] => CNY
[VAŽI ZA] => 1
[SREDNJI KURS] => 16.8711
),
[1] => Array
(
[ŠIFRA VALUTE] => 156
[NAZIV ZEMLJE] => Kina
[OZNAKA VALUTE] => CNY
[VAŽI ZA] => 1
[SREDNJI KURS] => 16.8711
)*/
Just use a simple loop over the array and check where the value of that specific key is CNY.
foreach($data as $row){
if($row['OZNAKA VALUTE'] == "CNY"){
echo $row['SREDNJI KURS'];
//or save it in an array or whatever you'd like to do with it.
}
}
Good afternoon. I am fairly new to php and so apologise in advance if my question is a little simplistic for this forum.
I have a PHP associative array with some nested sub arrays that I wish to echo as a table. Here is the array:
Array
(
[message] => Your request was executed successfully.
[errors] => [warnings] => Array ( )
[request_timestamp] => 04-08-2016 21:43:06
[response_timestamp] => 04-08-2016 21:43:06
[request_id] => abcd1234
[branch] => Array
(
[location_id] => 157499
)
[property] => Array
(
[0] => Array
(
[agent_ref] => WR37EF-453625
[update_date] =>
[client_id] => 60462053
[channel] => 2
)
[1] => Array
(
[agent_ref] => Prop950
[update_date] => 04-08-2016
[client_id] => 60457613
[channel] => 2
)
[prop2] => Array
(
[agent_ref] => WR40rp-632482
[update_date] => 04-08-2016
[client id] => 60461789
[channel] => 2
)
[prop3] => Array
(
[agent_ref] => WR38UU-243564
[update_date] => 04-08-2016
[id] => 60461807
[channel] => 2
)
[prop4] => Array
(
[agent_ref] => WR3HMWR3HM-145622
[update_date] => 04-08-2016
[client id] => 60462014
[channel] => 2
)
)
)
What I am trying [and miserably failing to achieve] is a table (preceded with a non-table Titles Area) in the following format....
Title Area:-
message: Your request was executed successfully.
errors: a, b, c,
request timestamp: 04-08-2016 21:43:06
response timestamp: 04-08-2016 21:43:06
request id: abcd1234
customer id: 157499
followed by ...
Table Design where:-
..Rows are sub array names : [0] ; [1] ; [2]; [3]
..Column Header Names are the sub array $keys: agent_ref; update_date; client id; channel
..the row-col values are the sub array $values.
I am aware I probably need to use the foreach loop method. But getting the key-value pair out of the nested arrays in the titles/table format I need I am really struggling with.
Any help or guidance would be hugely appreciated.
Thank you
Something like this:
<?php
extract($your_array);
echo "$message<br>";
echo "$request_id<br>"; ...etc.
..
$first=true;
echo "<table>";
foreach($property as $propkey=>$propdets) {
if ($first) { // on first row - do headings
$heads=array_keys($propdets); // gets the keys for headings
echo "<tr><th>Item</th>";
foreach($heads as $hdng) {
echo "<th>$hdng</th>";
}
echo "</tr>";
}
$first=false;
echo "<tr><td>$propkey</td>"; // first column is the key(Item) - 0,1,prop2,prop3 etc.
foreach ($propdets as $pdet) { // then loop through the details
echo "<td>$pdet</td>";
}
echo "</tr>";
}
echo "</table>";
...
...
?>
I am trying to create an array out of looped data. The variables contain looped data. All works fine, but when array is outputted, the index gets stuck at 0 and doesn't move up from 0 to 1 etc. I wonder what the problem is and how I can get this fixed.
Thanks.
$productinfo = array(
array(
"Productname" => "$productname",
"StarRating" => "$starrating",
"AddedValue" => "$addedvalue",
"ProductImage" => "$image",
"TotalPrice" => "$totalprice",
"ProductLink" => "$link" )
);
$productinfojson= json_encode($productinfo);
$output = json_decode($productinfojson, TRUE);
echo "<pre>";
print_r( $output );
echo "</pre>";
The above outputs:
Array
(
[0] => Array
(
[Procuctname] => Pencil Stack
[StarRating] => 3
[AddedValue] => Free Delivery
[ProductImage] =>
[TotalPrice] => 5.50
[ProductLink] => http://---.net/product
)
)
Array
(
[0] => Array
(
[Procuctname] => Block Bundle
[StarRating] => 4
[AddedValue] => Free Delivery
[ProductImage] =>
[TotalPrice] => 15
[ProductLink] => http://---.net/product
)
)
UPDATE if only one array is used.
code:
$productinfo = array(
"Productname" => "$productname",
"StarRating" => "$starrating",
"AddedValue" => "$addedvalue",
"ProductImage" => "$image",
"TotalPrice" => "$totalprice",
"ProductLink" => "$link" );
OUTPUT
Array
(
[Procuctname] => Pencil Stack
[StarRating] => 3
[AddedValue] => Free Delivery
[ProductImage] =>
[TotalPrice] => 5.50
[ProductLink] => http://---.net/product
)
Array
(
[Procuctname] => Block Bundle
[StarRating] => 4
[AddedValue] => Free Delivery
[ProductImage] =>
[TotalPrice] => 15
[ProductLink] => http://---.net/product
)
The issue stems straight from your array creation. There doesn't seem to be a loop anywhere in your code either....
Anyways, lets sort out your array creation. I assume you're getting the data from a database/data source and assigning it to variables, inputting it into an array? Well the way you currently have it, it's overwriting the first index element in the array.
Disclaimer: The below is pseudo code, until you update with your actual loop code..
$productinfo = array();
while($row = FETCH_DATA_FROM_SQL()) {
// assign it to variables here...?
$productinfo[] = array(
"Productname" => "$productname",
"StarRating" => "$starrating",
"AddedValue" => "$addedvalue",
"ProductImage" => "$image",
"TotalPrice" => "$totalprice",
"ProductLink" => "$link"
);
}
That will add each element to the new $productinfo array and you should be able to loop through the elements correctly.
One more thing to note, you're decoding your json like this:
$output = json_decode($productinfojson, TRUE);
That second parameter (TRUE), turns it into an associative array, not an object. So when you loop it as an object like below:
foreach($response->products->product as $product) {...
It isn't going to work. If you want it as an object, remove the second parameter (TRUE), otherwise loop it as an array:
foreach($response['products']['product'] as $product) {...
If my array states:
[mostPlayedGames] => Array ( [0] => stdClass Object ( [gameName] => Counter-Strike: Global Offensive [gameLink] => http://steamcommunity.com/app/730 [gameIcon] => http://cdn.akamai.steamstatic.com/steamcommunity/public/images/apps/730/69f7ebe2735c366c65c0b33dae00e12dc40edbe4.jpg [gameLogo] => http://cdn.akamai.steamstatic.com/steamcommunity/public/images/apps/730/d0595ff02f5c79fd19b06f4d6165c3fda2372820.jpg [gameLogoSmall] => http://cdn.akamai.steamstatic.com/steamcommunity/public/images/apps/730/d0595ff02f5c79fd19b06f4d6165c3fda2372820_thumb.jpg [hoursPlayed] => 28.0 [hoursOnRecord] => 527 [statsName] => CSGO ) [1] => stdClass Object ( [gameName] => Borderlands: The Pre-Sequel [gameLink] => http://steamcommunity.com/app/261640 [gameIcon] => http://cdn.akamai.steamstatic.com/steamcommunity/public/images/apps/261640/af5ef05eac8b1eb618e4f57354ac7b3e918ab1bd.jpg [gameLogo] => http://cdn.akamai.steamstatic.com/steamcommunity/public/images/apps/261640/df64c72fd335a03dbcc0a19b1f81acc8db1b94ba.jpg [gameLogoSmall] => http://cdn.akamai.steamstatic.com/steamcommunity/public/images/apps/261640/df64c72fd335a03dbcc0a19b1f81acc8db1b94ba_thumb.jpg [hoursPlayed] => 10.9 [hoursOnRecord] => 10.9 [statsName] => 261640 )
and I want to display info from the first part of the array( 0 ), how would I go about doing that if I was using code like this to display it:
echo "CS:GO Hours Played: {$user->mostPlayedGames???}, PHP_EOL;
Thank you for your time.
Your mostPlayedGames array doesn't seem like it is an stdClass of any variable named $user, so let's not over complicate it.
$mostPlayedGames = [mostPlayedGames] => Array ( [0] => stdClass Object ( [gameName]....[snippet]
Now that we have that clear:
echo "CS:GO Hours Played: ${mostPlayedGames[0]->hoursPlayed}".PHP_EOL;
You see, The first element in this is an array at position 0 so we must first move to that index position. The element at index 0 is an stdClass so then we can use the accessor method -> to grab properties of this object.