php foreach with one and a lot elements - php

For example I have code like this, I'm doing foreach loop and it works fine
foreach ( $response['albums']['album'] as $key=>$album ) {
echo($album['artist']['name']);
}
The content of $response is
[albums] => Array
(
[album] => Array
(
[0] => Array
(
[name] => Recovery
[playcount] => 1176206
)
[1] => Array
(
[name] => The Eminem Show
[playcount] => 948632
)
)
)
But, when the source of $response consist only from one element, i have such code, and foreach loop will not work.
[albums] => Array
(
[album] => Array
(
[name] => Doo-Wops & Hooligans
[playcount] => 1106732
)
)
So the question is how to let it work with minimal changes. Please excuse me for my beginner English.

Try like this..
if(array_key_exists(0,$response['albums']['album']))
{
foreach ( $response['albums']['album'] as $key=>$album ) {
echo($album['artist']['name']);
}
}
else
{
foreach ( $response['albums']['album'] as $album ) {
echo $album['name'];
}
}

foreach ( $response['albums'] as $album ) {
if(isset(album['name']))
{
echo $album['artist']['name'];
}
else
{
foreach($album as $val)
{
echo $val['artist']['name'];
{
}
}
That will work, although ideally your array should look like:
[albums] => Array
(
[0] => Array
(
[name] => Recovery
[playcount] => 1176206
)
[1] => Array
(
[name] => The Eminem Show
[playcount] => 948632
)
)
That way even if there is still one you can foreach it.

it will be better to keep consistent structure of input array $response to use single loop otherwise you can try following.
if(count($response['albums']) == 1){
foreach($response['albums'] as $key =>$val) {
echo $val['album']['name'];
}
}
else {
foreach ( $response['albums']['album'] as $key=>$album ) {
echo($album['artist']['name']);
}
}

Related

How to move a value up to a key, and remove a key. Array manipulation

I'm trying to change my array from this:
Array
(
[0] => Array
(
[BID_OPEN] => Array
(
[0] => 0.718282
)
)
[1] => Array
(
[BID_CLOSE] => Array
(
[0] => 1.654545
)
)
[2] => Array
(
[BID_OPEN] => Array
(
[0] => 1.654878
)
)
)
in to this:
Array
(
[BID_OPEN]
(
[0] => 0.718282
[1] => 1.654878
)
[BID_CLOSE]
(
[0] => 1.654545
[1] => 1.645845
)
)
I'm not sure how to begin. My code:
foreach($array as $keys=>$values)
{
if(!empty($array [$c]['BID_OPEN']))
{
$inital_part1 = array("BID_OPEN", $array [$c]['BID_OPEN']);
}
else
{
echo '';
}
if(!empty($array [$c]['BID_CLOSE']))
{
$inital_part2 = array("BID_CLOSE", $array [$c]['BID_CLOSE']);
}
else
{
echo '';
}
$array1[] = $inital_part1;
$array1[] = $inital_part2;
$c++;
}
I seem to get double outputs, so the foreach when I build arrays is giving me two times the required output. Google reckons it's because I have an array in my array somewhere but I'm precisely sure I don't.
The array came from an object stdclass and I don't know what that is, have googled but haven't found anything useful. Also I'm able to get some figures but only the initial values are correct, the rest of the data doesn't seem to come through. No doubt it's because I used an index[0] to get it working.
After hours any help would be great thanks.
As long as you have told us everything about your input array it can be done quite simply like this
<?php
$in = [ ['BID_OPEN' => [0.718282]],
['BID_CLOSE' => [1.654545]],
['BID_OPEN' => [1.654878]]
];
print_r($in);
$new = []; // new array we are building
foreach ($in as $abid) {
if (array_key_exists('BID_OPEN', $abid) ) {
$new['BID_OPEN'][] = $abid['BID_OPEN'][0];
}
if (array_key_exists('BID_CLOSE', $abid) ) {
$new['BID_CLOSE'][] = $abid['BID_CLOSE'][0];
}
}
print_r($new);
THE INPUT ARRAY: Is like yours
Array
(
[0] => Array
(
[BID_OPEN] => Array
(
[0] => 0.718282
)
)
[1] => Array
(
[BID_CLOSE] => Array
(
[0] => 1.654545
)
)
[2] => Array
(
[BID_OPEN] => Array
(
[0] => 1.654878
)
)
)
RESULT:
Array
(
[BID_OPEN] => Array
(
[0] => 0.718282
[1] => 1.654878
)
[BID_CLOSE] => Array
(
[0] => 1.654545
)
)
$c = 0;
$array1['BID_OPEN'] = [];
$array2['BID_CLOSE'] = [];
foreach($vartttttt as $tunips=>$ert)
{
$d = 0;
foreach($ert as $erts=>$val)
{
//$array[] = $erts;
if($erts == 'BID_OPEN')
{
array_push($array1['BID_OPEN'], $val[0]);
}
if($erts == 'BID_CLOSE')
{
array_push($array2['BID_CLOSE'], $val[0]);
}
$d++;
}
$c++;
}
$array = array_merge($array1, $array2);

PHP extract elements from an array which have a common name

I'd like to extract only up to a certain part of the name and test if it's set (isset)?
Specifically for largeImage_1, largeImage_2, etc..
This is what I've tried, but it doesn't seem to return or test.
if ($_POST['tutorial']) {
foreach ( $_POST['tutorial'] as $key => $value ) {
if ('largeImage' === substr($key, 0 , 10) )
{
echo $value;
}
}
}
Array
(
[title] => title
[tutorial] => Array
(
[1] => Array
(
[largeImage_1] => Array
(
[0] => image.png
[1] => image.png
)
)
[2] => Array
(
[largeImage_2] => Array
(
[0] => image.png
)
)
)
[name] => "";
)
You need a loop within another loop to access keys like 'largeImage_1', 'largeImage_2'.
if ($_POST['tutorial']) {
foreach ( $_POST['tutorial'] as $key => $value ) {
foreach ( $value as $k => $v ) {
if ('largeImage' === substr($k, 0 , 10) )
{
//your code here
}
}
}
}

accessing specific elements of arrays in a foreach loop

I apologize if this is a very simple question - I've read through tons of posts here, but my question is syntactically very hard to search for, so I haven't found an answer yet.
I have a json array that's output from a company's API:
[Result] => Array
(
[cData] => Array
(
[0] => Array
(
[Reqa] => ABCD
[Reqb] =>
[Reqc] => Plus
[dto] => Array
(
[0] => Array
(
[ComID] => 43292392
[Comment] => Dave
)
[1] => Array
(
[ComID] => 43292392
[Comment] => Bob
)
)
[XREFSearchOperation] => Exact
)
[1] => Array
(
[Reqa] => BCDE
[Reqb] =>
[Reqc] => A
[dto] => Array
(
[0] => Array
(
[ComID] => 19331186
[Comment] => Mike
)
[1] => Array
(
[ComID] => 19331186
[Comment] => Roger
)
)
[XREFSearchOperation] => Starts With
)
[2] => Array
(
[Reqa] => QQDT
[Reqb] =>
)
)
)
)
and I'm trying to access the [ComID] and [Comment] elements, if they exist, inside of a foreach loop and assign it to the variable $y
So far I have:
foreach ($json['Result']['cData']['dto'] as $i) {
$y = "{$i['ComID']}|{$i['Comment']}";
}
but this gives me zero results. I understand WHY, because in between ['cData'] and ['dto'] are [0], [1], [2] etc.. elements, and I don't know how to add a qualifier for those into the loop.
Update
This code works for most of the json response:
foreach ($json['Result']['cData'] as $i) {
if(array_key_exists('dto', $i)) {
foreach ($i['dto'] as $j) {
$y = "{$j['ComID']}|{$j['Comment']}";
} else {
}
}
However - I'm having one more small issue. If there are multiple [dto] responses, you'll have [dto][0][ComID] then [dto][1][ComID] and [dto][2][ComID], (like in the example above,) but if there's only ONE response, you'll have [dto][ComID] as there's no need for that middle array.
I tried writing if(array_key_exists('dto[0]' to execute one, then an else statement in the event dto[0] doesn't exist, but that didn't work. I need a way of NOT executing a foreach loop if there is no array underneath it to "foreachicize". Is there an if/else statement I can write to accommodate this?
Probably need a nested foreach:
foreach ($json['Result']['cData'] as $i) {
foreach($i['dto'] as $j) {
$y[] = "{$j['ComID']}|{$j['Comment']}"; //need an array here
}
}
For the update to the question. Check if $i['dto'][0] exists:
foreach ($json['Result']['cData'] as $i) {
if(isset($i['dto'][0]))) {
foreach($i['dto'] as $j) {
$y[] = "{$j['ComID']}|{$j['Comment']}";
}
} else {
$y[] = "{$j['ComID']}|{$j['Comment']}";
}
}
There might be a better way but I'm headed out.
Another approach:
foreach($json['Result']['cData'] as $cData)
{
foreach($cData['dto'] as $dto)
{
if(array_key_exists('ComID', $dto) && array_key_exists('Comment', $dto))
{
$y = "{$dto['ComID']}|{$dto['Comment']}";
}
}
}

unset row from multidimension array

I have two arrays:
array one is named as $input that output:
Array
(
[0] => Array
(
[reference_no] => 306334510
[archive_no] => 20140102900152506
)
[1] => Array
(
[reference_no] => 22936619
[archive_no] => 20140104900153643
)
[2] => Array
(
[reference_no] => 30211132
[archive_no] => 20140109001536461
)
[3] => Array
(
[reference_no] => 3890623027301
[archive_no] => 201401029001949791
)
)
and second array named as $active that will output:
Array
(
[0] => Array
(
[archive_no] => 20140102900152506
)
[1] => Array
(
[archive_no] => 20140104900153643
)
[2] => Array
(
[archive_no] => 2014010900133107
)
[3] => Array
(
[archive_no] => 2014010900152506
)
[4] => Array
(
[archive_no] => 2014010900153643
)
)
So first I need to check for duplicated rows and I check it by 'archive_no'.
So far this works fine, but now I need to remove those duplicated rows from $input array.
My unset does not seem to work.
code so far:
public function RemoveDublicatedRows($input, $active){
$output = array();
foreach ($input as $inp) {
foreach ($active as $act) {
if ($act['archive_no'] == $inp['archive_no']) {
$output[] = $act;
foreach ($output as $out){
if($inp['archive_no'] == $out['archive_no']){
$inp = array($inp);
unset($input[$inp]);
}
}
}
}
}
return $output;
}
You need to have an index instead of an array ($inp) here:
unset($input[$inp]);
Should be:
if($inp['archive_no'] == $out['archive_no'])
{
$index = array_search($inp, $input);
unset($input[$index]);
}
EDIT: some parts are useless in your code, here is a cleaned code:
public function RemoveDublicatedRows($input, $active)
{
$output = array();
foreach ($input as $inp)
{
foreach ($active as $act)
{
if ($inp['archive_no'] == $act['archive_no'])
{
$output[] = $act;
// maybe you should consider storing $act['archive_no'] instead ?
// It's up to you, depends on what you need...
$index = array_search($inp, $input);
unset($input[$index]);
}
}
}
return $output;
}

How To Access Values In Associative Array Using PHP

I have an array which is the result of a select query using Amazon SimpleDb.
Here is sample data when I print_r($result);
Array ( [0] => Array ( [Name] => 5140ede647e74
[Attributes] => Array (
[0] => Array ( [Name] => test_id [Value] => 5140ede647e74 )
[1] => Array ( [Name] => test_name [Value] => test1 )
[2] => Array ( [Name] => last_update [Value] => 1363209702 )
[3] => Array ( [Name] => created [Value] => 1363209702 ) ) ) )
If I want to extract the test_id and the test_name, how can I do it? I am currently doing the following
<?php foreach ($result as $item) {
echo $item['Attributes'][0]['Value'];
echo $item['Attributes'][1]['Value'];
} ?>
But I want to do it by referencing "test_id" and "test_name" because when I delete the domain where the data resides and re-enter the data, the order of each attribute can change so I can't trust that $item['Attributes'][0]['Value'] will always be the test_id
Thanks!
foreach ($result as $item) {
foreach ($item['Attributes'] as $keyvalue) {
if ($keyvalue['Name'] == 'test_id' || $keyvalue['Name'] == 'test_name') {
echo $keyvalue['Value'];
}
}
}
You need to recast the Array.
$newArray = array();
foreach ($result as $key=>$row)
{
foreach ($row['Attributes'] AS $row2)
{
$newArray[$key][$row2['Name']] = $row2['Value'];
}
}
EDIT: It depends on what you need to do - this is my preferred method if I plan on doing a lot of work with a resultset - I only need to iterate through the set once and then it's in a format where the data can be accessed quickly.
The following will run trough the last part of your array by reference. Therefore edits that you make are reflected in the $result array.
foreach ($result[0]['Attributes'] as &$item) {
if ($item['Name'] == 'test_id') // do something
}

Categories