Looping Through Multi-Dimensional Array in PHP - php

I've looked up a bunch of similar examples but still can't seem to figure out how loop through and echo the values from this array. Should be simple, but I'm dense. Help is appreciated.
array(2) { ["legend_size"]=> int(1) ["data"]=> array(2) { ["series"]=> array(2) { [0]=> string(10) "2014-01-17" [1]=> string(10) "2014-01-18" } ["values"]=> array(1) { ["Begin Session"]=> array(2) { ["2014-01-17"]=> int(1073) ["2014-01-18"]=> int(1122) } } } }
I'm trying to return the int values for the "values" array.

Given the name of your array is, for the sake of example, $mdarr, and that the construction of the array is going to be roughly the same every time, it is as simple as:
$values_i_want = $mdarr['data']['values'];
If the values array you are looking for is going to be in different array depths in different cases, recursion combined with type checking will do the trick:
//returns values array or nothing if it's not found
function get_values_array($mdarr) {
foreach ($mdarr as $key => $val) {
if ($key == 'values') {
return $val;
} else if (is_array($val)) {
return get_values_array($val);
}
}
}

Use the following as a base. I reconstructed your array so I could mess around with it.
$turtle = array('legend_size' => 'int(1)', 'data' =>array('series' => array('string(10) "2014-01-17"', '[1]=> string(10) "2014-01-18"'), 'values' => array('Begin_Session' =>array('2014-01-17' => 'int(1073)', '2014-01-18' => 'int(1122)'))));
// This is where you "navigate" the array by using [''] for each new array you'd like to traverse. Not sure that makes much sense, but should be clear from example.
foreach ($turtle['data']['values']['Begin_Session'] as $value) {
$match = array();
// This is if you only want what's in the parentheses.
preg_match('#\((.*?)\)#', $value, $match);
echo $match[1] . "<br>";
}

If the array structure is not going to change, and you just want the int values inside values, you could do the following:
//Create array
$some_array = array(
"legend_size" => 5,
"data" => array(
"series" => array(0 => "2014-01-17", 1 => "2014-01-18" )
"values" => array(
"Begin Session" => array("2014-01-17" => 1000, "2014-01-18" => 1000)
)
)
);
//Get values
foreach($some_array['data']['values'] as $key => $value)
{
if(is_array($value))
{
echo $key . " => ";
foreach($value as $key2 => $value2)
{
echo " " . $key2 . " => " . $value2;
}
}
else
{
echo $key . " => " . $value;
}
}
This will give you an output like this:
Begin Session =>
2014-01-17 => 1000
2014-01-18 => 1000

Related

Search values in php array

I have an array like this:
array(5) {
[0]=> array(1) { ["go-out"]=> string(7) "#0d4b77" }
[1]=> array(1) { ["cycling"]=> string(7) "#1472b7" }
[2]=> array(1) { ["diving"]=> string(7) "#1e73be" }
[3]=> array(1) { ["exploring"]=> string(7) "#062338" }
[4]=> array(1) { ["eating"]=> string(7) "#f79e1b" }
}
Let's say I have the first value like 'cycling', so how can I find the '#147217' value?
I have been trying a lot of combinations of
foreach ( $array as $key => list($key1 ,$val)) {
if ($key1 === $id) {
return $val;
}
}
But no luck.
Ideas?
You can use array_column -
array_column($your_array, 'cycling');
DEMO
You should also add the checks for key's existence.
you may still make one loop
$id = "cycling";
foreach($array as $val)
if(isset($val[$id])) echo $val[$id];
Demo on Evail.in
I have reformated tour code, try this, that works:
$array = array(
0 => array("go-out" => "#0d4b77"),
1 => array("cycling" => "#1472b7"),
2 => array("diving" => "#1e73be"),
3 => array("exploring" => "#062338"),
4 => array("eating" => "#f79e1b")
);
$id = "cycling";
foreach ($array as $key => $entry) {
if ($entry[$id]) {
echo $entry[$id];
}
}
$array = array(
0 => array("go-out" => "#0d4b77"),
1 => array("cycling" => "#1472b7"),
2 => array("diving" => "#1e73be"),
3 => array("exploring" => "#062338"),
4 => array("eating" => "#f79e1b")
);
$search = "cycling";
foreach ($array as $key => $entry)
if (isset($entry[$search]))
echo $entry[$search];
That works.
Nice day.

Decode json and foreach Shows key but not value

I cant seem to get the value from the foreach below. I need to basically create a loop where i can then create html buttons based on selections.
I have also added a snippet example only below this text to show what im trying to achieve within the foreach. I just need to work out how to extract the values so i can do that.
I am basically wanting to create a foreach loop that checks how many buttons the user has added and then display each button within the loop with a link in href and a custom button name. I will also have to check of they chose 1,2,3,4 from the showBtn value to determine what type of html to output.
if showBtn==1 { <a herf="btnMenuLink">btnName</a> }
if showBtn==3 { <a herf="btnPhone">btnName</a> }
I have the following code of which i have provided the outputs of the database content and also a var_dump just so you can see how the information is being stored.
The following code does output the key for me but it wont output the values. And i suspect its because my values are an array as well. How on earth would i create a loop within a loop within a loop and still achieve what i explained above?
<?php
$jsonresult = $column->links;
$array = json_decode($jsonresult,true);
// The databse TEXT field
/*{
"showBtn":["3","3"],
"btnMenuLink":["101","101"],
"btnArticleLink":["2","2"],
"btnPhone":["036244789","0404256478"],
"btnURL":["",""],
"btnName":["Office","Mobile"]
}*/
// The Var dump $array
/* array(6) {
["showBtn"] => array(2) {
[0] => string(1)
"3" [1] => string(1)
"3"
}["btnMenuLink"] => array(2) {
[0] => string(3)
"101" [1] => string(3)
"101"
}["btnArticleLink"] => array(2) {
[0] => string(1)
"2" [1] => string(1)
"2"
}["btnPhone"] => array(2) {
[0] => string(9)
"036244789" [1] => string(10)
"0404256478"
}["btnURL"] => array(2) {
[0] => string(0)
"" [1] => string(0)
""
}["btnName"] => array(2) {
[0] => string(6)
"Office" [1] => string(6)
"Mobile"
}
} */
foreach($array as $key => $value) { ?>
<?php echo $key;?>:<?php echo $value;?><hr/>
<?php } ?>
Im still kind of stuck on this,
please find below what im after:
$jsonresult = '{"showBtn":["3","3"],"btnMenuLink":["101","101"],"btnArticleLink":["2","2"],"btnPhone":["036244789","0404256478"],"btnURL":["",""],"btnName":["Office","Mobile"]}';
$array = json_decode($jsonresult,true);
foreach ($array as $key => $value) {
foreach ($value as $next_key => $next_value) {
echo $key.":".$next_key.":".$next_value."\n";
} }
// I want this
// if(showBtn==3) {
// echo '<a herf='tel:btnPhone'>btnName</a>';
// }
// the result would be
// Office Mobile
That would be because your $value is an array, not a set value. You'll need to loop it one more time:
foreach($array as $key => $values) {
foreach($values as $item) {
echo $key . ":" . $item;
}
echo "<hr />";
}
Example
foreach ($array1 as $key1 => $value1) {
foreach ($value as $key2 => $value2) {
echo "this is a nested loop";
}
}
So $value2 will contain the elements in the array.
Also, if you are not seeing any error or warning messages when you do echo $value; you should turn on error_reporting as it is extremely useful when developing.

New PHP array from multiple arrays inside a loop

To begin with I have an array (courses) like this:
array(2)
{
[0] => array(2)
{
["title"] => string "course1"
["code"] => string "001, 002, 003"
}
[1] => array(2)
{
["title"] => string "course2"
["ps_course_code"] => string "004"
}
}
Sometimes the 'code' will contain multiple codes as a comma separated string, other times 'code' will contain a single code.
To get individual codes I loop through the courses array and use explode to separate out the codes:
foreach($courses as $course) {
$courseInfo['code'] = explode(",",$course["code"]);
$courseInfo['title'] = $course["title"];
var_dump($courseInfo);
}
This gives me a new array for each course:
array(2)
{
["code"] => array(3)
{
[0] => string "001",
[1] => string "002",
[2] => string "003",
}
["title"] => string "course1"
}
array(2)
{
["code"] => array(1)
{
[0] => string "004"
}
["title"] => string "course2"
}
What I need though is a new array that contains every code and its title. So for some courses this means there will be multiple codes with the same title. E.g:
array(4)
{
[0] => array (2)
{
["code"] => string "001",
["title"] => string "course1"
}
[1] => array (2)
{
["code"] => string "002",
["title"] => string "course1"
}
[2] => array (2)
{
["code"] => string "003",
["title"] => string "course1"
}
[3] => array (2)
{
["code"] => string "004",
["title"] => string "course1"
}
}
I'm really struggling with this. Do I need another loop inside the first in order to create the final array?
foreach($courses as $course) {
$courseInfo['code'] = explode(",",$course["code"]);
$courseInfo['title'] = $course["title"];
// Another loop to create final array?
foreach($courseInfo as $value) {
$final['code'] = $value['code']; // I know this doesn't work!
$final['title'] = $value['title'];
}
}
var_dump($final);
I know this is long and I probably haven't explained this very well, so apologies!
You can get the desired output by looping over your first array:
$final = array();
foreach ($courses as $course) {
$codes = array_map('trim', explode(',', $course['code']));
foreach ($codes as $c) {
$final[] = array('code' => $c, 'title' => $course['title']);
}
}
Demo
You'd need to loop around the array of courses, not the full array.
i.e. something like this:
$i = 0;
foreach($courses as $course) {
$codes = explode(",",$course["code"]);
foreach($codes as $code) {
$final[$i]['code'] = $code;
$final[$i]['title'] = $course['title'];
$i++;
}
}
var_dump($final);
Easiest way to create array from the array value code is to loop through the array and explode the values, like you did.
$new_array = array(); //optionally for adding to new array
foreach($courses as $course)
{
$code = explode(',', $course['code']);
$trimmed_code = array_walk($code, function($value)
{
//trim the value to remove spaces before and after value
return trim($value);
});
$course['code'] = $trimmed_code;
//code for optionally add to new array
$new_array[] = array(
'code' => $code,
'title' => $course['title'],
);
}
foreach($courses as $course) {
$codes = explode(",",$course["code"]);
for($i=0;$i<count($codes); $i++){
$courseInfo['code'] = $codes[i];
$courseInfo['title'] = $course["title"];
}
var_dump($courseInfo);
}

PHP Array Rename Dynamic Array Keys

I am needing to rename dynamic array keys, and create a new array.
Here is the array as given:
array(21)
{
["0161"] =>
array(5)
{
["L_NAME0161"] =>
string(13) "john%20Hewett"
["L_TRANSACTIONID0161"] =>
string(17) "50350073XN1446019"
["L_AMT0161"] =>
string(6) "8%2e50"
["L_FEEAMT0161"] =>
string(9) "%2d0%2e55"
["L_NETAMT0161"] =>
string(6) "7%2e95"
}
["08591"] =>
array(5)
{
["L_NAME08591"] =>
string(18) "Norbert%20Bendixen"
["L_TRANSACTIONID08591"] =>
string(17) "1WN98871MS4263823"
["L_AMT08591"] =>
string(6) "8%2e50"
["L_FEEAMT08591"] =>
string(9) "%2d0%2e55"
["L_NETAMT08591"] =>
string(6) "7%2e95"
}
}
Here is the code I am using which is not working for me:
foreach ($reb AS $newrebarray)
{
foreach ($newrebarray as $ke => $val)
{
if (preg_match("/L_NETAMT/i", $ke))
{
$newarrayreb1 = array('Net' => $val);
}
if (preg_match("/L_TRANSACTIONID/i", $ke))
{
$newarrayreb1 = array('TransactID' => $val);
}
if (preg_match("/L_NAME/i", $ke))
{
$newarrayreb1 = array('Name' => $val);
}
}
}
notice that the array keys are dynamic, I want to create a new array with static keys, and the associated values. When I run the code, I get five different arrays.
First I would define a function that does replacement based on a captured memory segment of a regular expression:
function do_translate($match)
{
switch ($match[1]) {
case 'L_NAME':
return 'Name';
case 'L_NETAMT':
return 'Net';
case 'L_TRANSACTIONID':
return 'TransactID';
}
// in all other cases, return the full match
return $match[0];
}
Then iterate over the blocks, send the array keys through a translation pass and then recombine the new keys with the existing values:
foreach ($reb as $id => $data) {
$new_keys = preg_replace_callback('/^(L_[A-Z]+)' . preg_quote($id) . '$/i', 'do_translate', array_keys($data));
// create the new array with translated keys
$reb[$id] = array_combine($new_keys, $data);
}
I noticed that the array keys were a combination of the field and the product id (I guess), so I've used that knowledge to strengthen the regular expression
Not tested, haven't fully woken up yet, so this'll probably kick your dog and delete all your savegames:
$translations = array(
'L_TRANSACTIONID' => 'Translation',
'L_NAME' => 'Name',
'L_NETAMT' => 'Net'
);
foreach($array as $parentkey => $subarray) {
foreach($subarray as $subkey => $val) {
if (preg_match('/^(L_.*?)\d*$/', $matches)) {
$newKey = $translations[$matches[1]];
$array[$parentkey][$newkey] = $val;
unset($array[$parentkey][$subkey]);
}
}
}

PHP Reconstruct Array

I need to reconstruct an array. Here is the original array:
array(8) {
[0] => array(1)
{
["L_TRANSACTIONID0"] => string(17) "62M97388AY676841D"
}
[1] => array(1)
{
["L_TRANSACTIONID1"] => string(17) "9FF44950UY3240528"
}
[2] => array(1)
{
["L_STATUS0"] => string(9) "Completed"
}
[3] => array(1)
{
["L_STATUS1"] => string(9) "Completed"
}
}
I would like to reconstruct it to be as such:
array(2) {
[0] => array(2)
{
["L_TRANSACTIONID0"] => string(17) "62M97388AY676841D"
["L_STATUS0"] => string(9) "Completed"
}
[1] => array(1)
{
["L_TRANSACTIONID1"] => string(17) "9FF44950UY3240528"
["L_STATUS1"] => string(9) "Completed"
}
}
Notice that the KEYS both match with the numeric representation... Is this at all possible?
edit:
here is my code I am using:
foreach($comparison as $key => $val) {
$findme1 = 'L_TRANSACTID'.$i++;
$findme2 = 'L_STATUS'.$c++;
$arrDisable = array($findme1,$findme2);
if( in_array($key, $arrDisable ) ) {
unset( $comparison[ $key ][$val]);
}
if( in_array($key, $arrDisable) ) {
unset( $comparison[ $key ][$val]);
}
}
Try this
$labels = array('L_TRANSACTIONID', 'L_STATUS');
$res = array();
foreach($arr as $val) {
$key = str_replace($labels, '', key($val));
$res[$key] = isset($res[$key]) ? array_merge($res[$key], $val) : $val;
}
print_r($res);
http://codepad.org/MwqTPqtA
If you are certain the the vector cointains pairs L_TRANSACTIONIDn / L_STATUSn keys,that is to say, for each transactionID, there is a corresponding status, what you can do, is to get the number of id/status records (which should equal the length of the initial array, divided by two), and compose the resultin keys, by increasing the current element count.
Could look something like this:
$numItems = sizeof($myInitialArray) / 2;
$newArray = array();
for($i = 0; $i < $numItems; $i++)
{
$itemID = $i * 2; // since we're getting id/status pairs, we're using a step equal to 2
$newArray[] = array(
("L_TRANSACTIONID" . $i) => $myInitialArray[$itemID], // this is the id value
("L_STATUS" . $i) => $myInitialArray[$itemID + 1] // this is the status for that id
);
}
Hope this helps. Have a great day!

Categories