How can I output only the values of subarrays? - php

I have an array and I want to output some data:
array(4) {
[123]=>
array(2) {
["color"]=>
string(3) "red"
["name"]=>
string(5) "harry"
}
[345]=>
array(2) {
["color"]=>
string(4) "blue"
["name"]=>
string(4) "fred"
}
["animal"]=>
string(5) "horse"
["plant"]=>
string(4) "tree"
}
This is my solution, which I have the feeling is very unsmart:
echo "<b>These are all the colors:</b><br>";
foreach ($properties as $key => $val) {
if ($key != "plant" AND $key != "animal"){
echo $val['color']."<br>";
}
}
echo "<b>This is the animal:</b><br>";
foreach ($properties as $key => $val) {
if ($key == "animal"){
echo $val."<br>";
}
}
echo "<b>This is the plant:</b><br>";
foreach ($properties as $key => $val) {
if ($key == "plant"){
echo $val."<br>";
}
}
It gives me the desired result...
These are all the colors:
red
blue
This is the animal:
horse
This is the plant:
tree
...but I thought maybe you know a more simple solution. I am sure it must be possible to talk only to subarrays, but I couldn't find a way to do it.

Since php 5.5, you can use array_column:
$color = array_column($properties, 'color');
Since php 5.3, you can use array_map with an anonymous function, like this:
$color = array_map(function ($ar) {return $ar['color'];}, $properties);
print_r($color);
exit;

I think, Use Switch in foreach and it will help for this problem.
foreach ($properties as $key => $val) {
switch($key){
case '':
break;
}
}

Related

Re-arranging and combining an array

I'm having an issue when I dump the array below. This dumps several arrays. Some are 2 some are 3, which complicates it even more. Basically what I want I put below. I have tried array_push, array_combine, array_merge, several different ways including $array[$param] = $insertValue and I'm stuck. I am open to creating a brand new array too.
Please note not all arrays are counts of 3 but always return at least 1.
Original array:
array(3) {
[0]=>
array(2) {
["contact_id"]=>
string(9) "CONTACTID"
["contact_id_content"]=>
string(19) "123456789123456"
}
[1]=>
array(2) {
["sm_owner"]=>
string(9) "SMOWNERID"
["sm_owner_content"]=>
string(19) "123456798452"
}
[2]=>
array(2) {
["contact_owner"]=>
string(13) "Contact Owner"
["contact_owner_content"]=>
string(16) "Jane Doe"
}
Array desired:
array(3) {
[0]=>
array(6) {
["contact_id"]=>
string(9) "CONTACTID"
["contact_id_content"]=>
string(19) "123456789123456"
["sm_owner"]=>
string(9) "SMOWNERID"
["sm_owner_content"]=>
string(19) "123456798452"
["contact_owner"]=>
string(13) "Contact Owner"
["contact_owner_content"]=>
string(16) "Jane Doe"
}
try this code:
$NewArray = array();
foreach($OriginalArray as $value) {
$NewArray[] = array_merge($value,$NewArray);
}
or you can use array_merge_recursive
let $result = [];
foreach ($yourarray as $key => $value) {
$result = $value;
}
var_dump($result);
Here you go: How to Flatten a Multidimensional Array? – Barmar 23 mins ago
function flatten($array)
{
return array_reduce($array, function($acc, $item){
return array_merge($acc, is_array($item) ? flatten($item) : [$item]);
}, []);
}
// loop the individual fields
for ($i=0; $i<count($row_data); $i++) {
$newArray = flatten([$i => $response_row]);
}
Try something like this:
function flatten(array $array) : array
{
$newArray = [];
foreach ($array as $subArray) {
foreach ($subArray as $key => $value) {
$newArray[$key] = $value;
}
}
return $newArray;
}

Assign Number to Foreach Variables

I want to create a list of variables from a foreach loop. I have an array like so
array(5) {
[0]=> string(105) "http://a4.mzstatic.com/us/r30/Purple5/v4/06/f2/02/06f20208-1739-4fda-c87f-171d73b912a7/screen480x480.jpeg"
[1]=> string(105) "http://a1.mzstatic.com/us/r30/Purple1/v4/53/89/0b/53890b90-c6a5-4db3-cfb9-d6314bf9cfd1/screen480x480.jpeg"
[2]=> string(105) "http://a3.mzstatic.com/us/r30/Purple1/v4/8f/31/b3/8f31b351-c9d7-e545-0ace-e09fcb390264/screen480x480.jpeg"
[3]=> string(105) "http://a5.mzstatic.com/us/r30/Purple3/v4/e7/5f/de/e75fde7b-dc5f-5b26-e531-abf07c409317/screen480x480.jpeg"
[4]=> string(105) "http://a1.mzstatic.com/us/r30/Purple3/v4/27/ce/c6/27cec64e-7e6d-7135-cc76-d0132151dadb/screen480x480.jpeg"
}
and I'd like to assign each to it's own variable. I want the final output to be something like
$var0 = "first array url";
$var1 = "second array url";
etc...
I think I want something like this but it's not quite the right syntax.
foreach ($array as $key => $value) {
$var[$key] = $value;
}
Any ideas?
foreach($array as $key => $value) {
${"var{$key}"} = $value;
}
The function you are searching for is extract.
Just use it after your foreach loop given in your example.
$vars = [];
foreach ($array as $i => $value) {
$vars['var'.$i] = $value;
}
extract($vars);

How to loop and get serialized values from database with php

I'm developing a pizza's restaurant ecommerce and now I'm trying to get the size (Familiar) and the ingredients (Pernil dol�, Bac�, Emmental) of a pizza that was ordered previously. The data I want to get (the italic values in this paragraph) becomes serialized from database:
a:4:{s:10:"attributes";a:2:{s:6:"Tamany";a:1:{i:3;s:8:"Familiar";}s:11:"Ingredients";a:3:{i:318;s:12:"Pernil dol�";i:270;s:5:"Bac�";i:294;s:8:"Emmental";}}s:9:"shippable";s:1:"0";s:4:"type";s:5:"pizza";s:6:"module";s:10:"uc_product";}array(4) { ["attributes"]=> array(2) { ["Tamany"]=> array(1) { [3]=> string(8) "Familiar" } ["Ingredients"]=> array(3) { [318]=> string(11) "Pernil dol�" [270]=> string(4) "Bac�" [294]=> string(8) "Emmental" } } ["shippable"]=> string(1) "0" ["type"]=> string(5) "pizza" ["module"]=> string(10) "uc_product" }
I discovered 'unserialized' php method and I tried this:
$attr = $row['data']; // data from database
$data = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $attr); // I did this because I get some errors...
After I did that, I got this multidimensional array (a bit more human readable):
array(4) { ["attributes"]=> array(2) { ["Tamany"]=> array(1) { [3]=> string(8) "Familiar" } ["Ingredients"]=> array(3) { [318]=> string(11) "Pernil dol�" [270]=> string(4) "Bac�" [294]=> string(8) "Emmental" } } ["shippable"]=> string(1) "0" ["type"]=> string(5) "pizza" ["module"]=> string(10) "uc_product" }
Next step was try to loop the resulting data with a foreach loop, like the following:
foreach($data['attributes'] as $item)
{
print '<ul>';
foreach($item as $value)
{
print_r('<li>' . $value . '</li>');
}
print '</ul>';
}
I'm a php beginner PHP developer and I can't figure out how can I loop this array in order to get the values I need. I'm getting this error:
Warning: Invalid argument supplied for foreach() in /home/my_host/public_html/dev.mysite.com/inc/file.php on line 79
Can anybody tell me how I have to loop this array to get the data?
Any help will be very, very appreciated.
Best regards,
I created this example for you. First I declared an array which believe mimics the array you have to parse. Then I looped through and outputed the contents of the array.
<?php
$array = array(
0 => array(
'0' => 'John Doe',
'1' => 'john#example.com'
),
1 => array(
'0' => 'Jane Doe',
'1' => 'jane#example.com'
),
);
foreach ($array as $key => $value) {
$thisArray = $array[$key];
print_r('<ul>');
foreach ($thisArray as $key2 => $value){
print_r('<li>'.$thisArray[$key2].'</li>');
}
print_r('</ul>');
}
?>
Finally, and based on the answer of #Gregory Hart, I reached my goal. This is the final code that makes it possible in my particular case:
$data = $row['data'];
$attrib = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $data);
$attr = unserialize($attrib);
foreach ($attr as $key => $value)
{
print_r('<ul>');
$thisArray = $attr[$key];
foreach ($thisArray as $key2 => $value2)
{
print_r('<li>' . $key2 . ': ');
$thisArray2 = $attr[$key][$key2];
foreach ($thisArray2 as $key3 => $value3)
{
if ($key2 == 'Tamany')
print_r('<span class="label label-warning">' . utf8_encode($thisArray2[$key3]) . '</span> ');
if ($key2 == 'Ingredients')
print_r('<span class="label label-success">' . utf8_encode($thisArray2[$key3]) . '</span> ');
if ($key2 == 'Salsa')
print_r('<span class="label label-primary">' . utf8_encode($thisArray2[$key3]) . '</span> ');
}
print '</li>';
}
print_r('</ul>');
}
Thanks for you help!
Try this logic:
$data_unserialize = unserialize($row->data);
foreach ($data_unserialize as $data_key => $data_value) {
if($data_key =='size')
{
$thisArray = $data_unserialize[$data_key ];
foreach ($thisArray as $key2 => $value2){
if($key2=='attributes')
{
switch ($value2)
{
case "Pernil dol�":
echo'Pernil dol �';
break;
case "Emmental":
echo'Emmental';
break;
default:
echo 'Nothing';
}
}
}
}
}
NB:- And remove the break; from switch statement to display all ingrediants.

Using a variable outside foreach with if statement?

This code should explain it all..
foreach($this->sections as $k => $section){
$preview = array();
foreach ($section['fields'] as $k => $type) {
$preview[] = $type['type'];
}
if ($preview == 'header_preview'){
echo $preview;
// I will loop content here based on the $section loop NOT the $type loop
}
}
I just need to get each $section['fields'] then outside that loop, which again gets a list of all the $section['fields'] then use one of those field types to create an if statement. The above is non working, I will show you working code here.
foreach($this->sections as $k => $section){
foreach ($section['fields'] as $k => $type) {
if ($type['type'] == 'header_preview'){
//I work but im in a nested loop I need out
}
}
//The main loop here.. the above loop is just to setup data to use inside this loop? Make sense? I hope!
}
I hope this makes sense...
Snippet of var_dump $this->sections
array(26) { ["general"]=> array(3) { ["title"]=> string(7) "General" ["icon"]=> string(106) "img/icons/sub.png" ["fields"]=> array(5) { [0]=> array(6) { ["id"]=> string(10) "responsive" ["type"]=> string(6) "switch" ["title"]=> string(35) "Responsive" ["desc"]=> string(10) "Responsive" ["options"]=> array(2) { [1]=> string(2) "On" [0]=> string(3) "Off" }
It could be possible $k has been duplicated and therefore the loop doesn't know what to do. You can try changing $k to $x, see if it works.
foreach($this->sections as $k => $section){
$preview = array();
foreach ($section['fields'] as $x => $type) {
$preview[] = $type['type'];
}
foreach($preview as $elem){
if ($elem == 'header_preview'){
echo($elem);
}
}
}
Hmm... Maybe
foreach($this->sections as $k => $section){
$preview = array();
foreach ($section['fields'] as $x => $type) {
$preview[] = $type['type'];
}
if(!in_array('header_preview', $preview)){
// Here $preview DOES NOT contain 'header_preview'
// Do stuff
}
}
$header_preview=false;
foreach($this->sections as $k => $section){
$header_preview=false;// reset the var $header_preview
foreach ($section['fields'] as $k => $type) {
if ($type['type'] == 'header_preview') $header_preview = true;
}
if($header_preview==true){
//here you can add or extract from this array that has `header_preview` value for one of it's field type
}
}

Foreach loop working, but outputting "invalid argument"?

I hope to give enough information here, but I am confused as to why the foreach loop works, it gets each data and outputs it in an li but I am getting an invalid argument error?
Here is the result of the var_dump
array(1) { ["questions"]=>
array(2) { ["title"]=> string(5) "Keanu" [1]=>
array(1) { ["questionlist"]=> array(2) { [0]=>
array(1) {
["a-question"]=> string(1) "1" } [1]=> array(1) {
["a-question"]=> string(5) "civil" } } } } }
Here is my foreach statement
foreach($questions['questions'] as $key => $value){
foreach($value['questionlist'] as $key => $subquestion){ //line 119
echo '<li>'.$subquestion['a-question'].'</li>';
}
}
$questions is a variable used to get the data from the database like this.
$questions = $wpdb->get_row("SELECT * FROM $table_name ORDER BY id DESC LIMIT 1" , ARRAY_A);
The data comes from ajax, I modify the ajax $_POST like this before sending to the database.
// Add modifications
$questions['questions'] = $_POST['questions']['data'];
// DB data
$name = $wpdb->escape($questions['questions']['title']);
$data = $wpdb->escape(json_encode($questions));
Screenshot:
I am not sure why I am getting the invalid argument, I suspect its because the array may not be formatted properly, if you need any more information let me know.
A Solution: Thanks to #didierc
I used his code and modified it a bit to display my data in a loop, basically all I did was add another foreach.
foreach($questions['questions'] as $key => $value){
if(is_array($value) && isset($value[ 'questionlist'])){
foreach($value as $key => $subquestion){ //line 119
foreach ($subquestion as $key => $value){
// This loops all the ['a-question'] data
echo '<li>''.$value['a-question'].''</li>';
}
}
}
}
Try this:
foreach ($questions['questions'] as $key => $value) {
if (is_array($value) && isset($value[ 'questionlist'])) {
foreach ($value['questionlist'] as $subnum => $subquestion) {
foreach ($subquestion as $qtitle => $qanswer) {
With variable names hopefully explicit enough. That should get you started.
NB: The data is probably easier to understand when formatted as below:
array(1) {
["questions"]=> array(2) {
["title"] => string(5) "Keanu"
[1] => array(1) {
["questionlist"]=> array(2) {
[0]=> array(1) {
["a-question"]=> string(1) "1"
}
[1]=> array(1) {
["a-question"]=> string(5) "civil"
}
}
}
}
}

Categories