Decode json and foreach Shows key but not value - php

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.

Related

How to update data in a table in an array form in Vue.js

So I have a query below that only works if I only have one data passed or to update, but when there's 2 or more, it's not working anymore:
public function update($id){
$data = $this->request->all();
$result = array($data);
foreach($result as $x => $x_value) {
$emp_key = $x_value['data'];
}
DB::table('employee')->where('emp_key', $emp_key)->update([
'group_code' => $id,
]);
}
I want to update the group_code of each emp_key to 0.
Sample result when I var_dump($result), following is the result:
array(1) {
[0]=>
array(1) {
["data"]=>
array(2) {
[0]=>
string(6) "123bcd"
[1]=>
string(6) "635bdd"
}
}
}
print_r OUTPUT:
Array
(
[data] => Array
(
[0] => 123bcd
[1] => 635bdd
)
)
Can anyone help me on this please?
Just move your update query inside the foreach loop:
foreach($data['data'] as $x => $emp_key) {
DB::table('employee')->where('emp_key', $emp_key)->update([
'group_code' => $id,
]);
}
What your previous code was doing was that the $emp_key variable was only storing the last value in your loop thus it was the only one being updated by your query

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.

Change indexed Array to Associative Array PHP

I have an array from json_decode. And i want to reformat it.
this is my array format.
["Schedule"]=>array(1) {
["Origin"]=>
string(3) "LAX"
["Destination"]=>
string(2) "CGK"
["DateMarket"]=>
array(2) {
["DepartDate"]=>
string(19) "2015-02-01T00:00:00"
["Journeys"]=>
array(6) {
[0]=>
array(6) {
[0]=>
string(2) "3210"
[1]=>
string(14) "Plane Name"
[2]=>
string(8) "20150201"
[3]=>
string(8) "20150201"
[4]=>
string(4) "0815"
[5]=>
string(4) "1524"
}
}
}
And i want change the indexed array to associative with foreach function.
And here is my PHP code
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$value->Name= $value[1];
}
But i got an error "Attempt to assign property of non-object on line xXx..
My Question is, how to insert a new associative array to indexed array like the example that i've provide.
UPDATE : I've tried this solution
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$value['Name']=$value[1];
}
But my array format still the same, no error.
In this line:
$value->Name= $value[1];
You expect $value to be both object ($value->Name) and array ($value[1]).
Change it to something like:
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$response->Schedule['DateMarket']['Journeys'][$key]['Name'] = $value[1];
}
Or even better, without foreach:
$keys = array(
0 => 'Id',
1 => 'Name',
2 => 'DateStart',
3 => 'DateEnd',
4 => 'HourStart',
5 => 'HourEnd',
);
$values = $response->Schedule['DateMarket']['Journeys'];
$response->Schedule['DateMarket']['Journeys'] = array_combine( $keys , $values );
Array_combine makes an array using keys from one input and alues from the other.
Docs: http://php.net/manual/en/function.array-combine.php
Try this:
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$value['Name'] = $value[1];
}
You want to create new array index, but try to create new object.
foreach ($response->Schedule['DateMarket']['Journeys'] as $key => $value) {
$value['Name'] = $value[1];
}

Looping Through Multi-Dimensional Array in 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

How to convert a PHP array to a specific Javascript format

I know this must be very basic but I really don't know how to solve this. I want to turn a php array to the following notation to be used inside a javascript script. These are countries which are passed to the js script in the initialization.
Source notation (PHP)
array(3) { [0]=> array(1) { ["code"]=> string(2) "AR" } [1]=> array(1) { ["code"]=> string(2) "CO" } [2]=> array(1) { ["code"]=> string(2) "BR" } }
Desired outcome (JS)
[ "AR", "FK","CO", "BO", "BR", "CL", "CR", "EC", "GT", "HN", "LT", "MX", "PA", "PY", "PE", "ZA", "UY", "VE"]
I can reformat the origin PHP array as desired, what I need to know is how to format it to get the desired outcome.
I am using the following code to pass the array to js:
echo "<script>var codes = " . json_encode($codes) . ";</script>";
Looks like the following would work for you:
<?php
$arr[0]['code'] = 'AR';
$arr[1]['code'] = 'CO';
$arr[2]['code'] = 'BR';
print_r($arr);
function extract_codes($var) { return $var['code']; }
print_r(array_map('extract_codes', $arr));
echo json_encode(array_map('extract_codes', $arr));
?>
Output:
Array
(
[0] => Array
(
[code] => AR
)
[1] => Array
(
[code] => CO
)
[2] => Array
(
[code] => BR
)
)
Array
(
[0] => AR
[1] => CO
[2] => BR
)
["AR","CO","BR"]
It works by mapping each of the two-letter codes down to a normal one-dimensional array, then passing it to json_encode.
Going with array_reduce:
$output = array_reduce($array, function($result, $item){
$result[] = $item['code'];
return $result;
}, array());
echo json_encode($output);
You need to loop through your PHP associative array and set the appropriate variables.
Like this:
$item = ''; // Prevent empty variable warning
foreach ($php_array as $key => $value){
if (isset($key) && isset($value)) { // Check to see if the values are set
if ($key == "code"){ $item .= "'".$value."',"; } // Set the correct variable & structure the items
}
}
$output = substr($item,'',-1); // Remove the last character (comma)
$js_array = "[".$output."]"; // Embed the output in the js array
$code = $js_array; //The final product

Categories