logo
down
shadow

Find key in array in a foreach


Find key in array in a foreach

By : Erica Fran Mateo
Date : November 22 2020, 02:42 PM
To fix this issue You could always loop through the array twice and break out of the first loop once you find the d_payment_fee code:
code :
$dpaymentfeetext = '';
$dpaymentfeevalue = '';

foreach ($total_data as $data)
{
    if ($data['code'] == 'd_payment_fee')
    {
        $dpaymentfeetext = ' - '.$data['title'];
        $dpaymentfeevalue = $data['value']/1.20;
        break;
    }
}

// Then do your original loop here


Share : facebook icon twitter icon
Find last value of array in foreach cicle

Find last value of array in foreach cicle


By : sdkask
Date : March 29 2020, 07:55 AM
like below fixes the issue I've data stored in a array ($rows). For read the array and genarate a dinamic table I use foreach function. , Try this:
code :
foreach ($rows as $key => $row) {
    $end = end($rows) === $row ? 'class="last"' : '';
    echo "<tr $end>";
    echo "<td>" . $row['field1'] . "</td>";
    echo "<td>" . $row['field2'] . "</td>";
    echo "<td>" . $row['filed3'] . "</td>";
    echo "</tr>"; 
}
foreach ($rows as $key => $row) {
    $end = end($rows) === $row && $key === key($rows) ? 'class="last"' : '';

    // ...
I want to find my value in an array using just 1 foreach

I want to find my value in an array using just 1 foreach


By : Ronald Dutch Raymond
Date : March 29 2020, 07:55 AM
Any of those help PHP code demo
code :
<?php
ini_set("display_errors", 1);
$search=2;
$result=null;
$myarr = array(
    '1',
    '2',
    '3',
    '4-7',
    '9',
    '10',
);
echo search_in_array($myarr,$search);
function search_in_array($myarr,$search)
{
    $result=false;
    array_map(function($number) use ($myarr,$search, &$result){
        if(preg_match("/^(\d+)\-(\d+)$/", $number,$matches))
        {
            if(in_array($search,range($matches[1],$matches[2]))) 
            {
                $result= true;
            }
        }
        elseif(preg_match("/^(\d+)$/", $number,$matches))
        {
            if(in_array($search,$myarr))
            {
                $result= true;
            }   
        }
    }, $myarr);
    return $result;
}
Trying to filters an array of objects by an array of numbers with find my index and forEach doesnt work

Trying to filters an array of objects by an array of numbers with find my index and forEach doesnt work


By : user2475261
Date : March 29 2020, 07:55 AM
Any of those help If I understood right, you want to filter out some numbers from the contact's phone numbers. One solution to this can be approached using Array.map() over the contacts array and replace the phoneNumbers array with a new filtered array. For the filtering procedure we can use Array.filter() and Array.includes() to check if a phone number belong to the list of numbers you want to filter out.
code :
const contacts = [
  {
    "company": "Financial Services Inc.",
    "contactType": "person",
    "firstName": "Hank",
    "id": "2E73EE73-C03F-4D5F-B1E8-44E85A70F170",
    "imageAvailable": false,
    "jobTitle": "Portfolio Manager",
    "lastName": "Zakroff",
    "middleName": "M.",
    "name": "Hank M. Zakroff",
    "phoneNumbers": [
      {
        "countryCode": "us",
        "digits": "5557664823",
        "id": "337A78CC-C90A-46AF-8D4B-6CC43251AD1A",
        "label": "work",
        "number": "(555) 766-4823",
      },
      {
        "countryCode": "us",
        "digits": "7075551854",
        "id": "E998F7A3-CC3C-4CF1-BC21-A53682BC7C7A",
        "label": "other",
        "number": "(707) 555-1854",
      },
    ],
  },
  {
    "contactType": "person",
    "firstName": "David",
    "id": "E94CD15C-7964-4A9B-8AC4-10D7CFB791FD",
    "imageAvailable": false,
    "lastName": "Taylor",
    "name": "David Taylor",
    "phoneNumbers": [
      {
        "countryCode": "us",
        "digits": "5556106679",
        "id": "FE064E55-C246-45F0-9C48-822BF65B943F",
        "label": "home",
        "number": "555-610-6679",
      },
    ],
  },
];

// Numbers to filter out.
const numsToFilterOut = [5557664823];

let res = contacts.map(contact =>
{
    contact.phoneNumbers = contact.phoneNumbers.filter(
        // Unary plus is used to coerces (cast) the string to number.
        phone => !numsToFilterOut.includes(+phone.digits)
    );

    return contact;
});

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Php array find same value inside foreach

Php array find same value inside foreach


By : user3391193
Date : March 29 2020, 07:55 AM
hope this fix your issue , Is this the solution you're looking?
code :
<?php

$data = [
    [
        "id" => 1,
        "influencer_user_id" => 4,
        "content_data" => '{"Reach":"300","Views":"320","Views through rate":"350","Shares":"350"}',
    ],
    [
        "id" => 2,
        "influencer_user_id" => 4,
        "content_data" => '{"Reach":"100","Likes":"100","Views":"100"}',
    ],
    [
        "id" => 3,
        "influencer_user_id" => 5,
        "content_data" => '{"Reach":"350"}',
    ],
]; 

$result = array();

// first, group the influencer_user_id
foreach ($data as $element) {
    $result[$element['influencer_user_id']][] = $element;
}

// second, calculate content_data
$result = array_map(function($element){
    $element = array_reduce($element, function($carry, $item){

        // convert to array
        $content_data = json_decode($item['content_data'], true);

        // convert content_data to integer values
        $content_data = array_map('intval', $content_data);

        $item['content_data'] = $content_data;

        if(empty($carry))
            return $item;

        // compute content_data sum
        array_walk($item['content_data'], function(&$value, $key) use ($carry){
            if(isset($carry['content_data'][$key])){
                $value += $carry['content_data'][$key];
            }
        });

        return $item;
    });

    // convert content_data back to json
    $cdata = $element['content_data'];
    $element['content_data'] = json_encode($cdata);

    return $element;
}, $result);

$result = array_values($result);

print_r($result);
Array
(
    [0] => Array
        (
            [id] => 2
            [influencer_user_id] => 4
            [content_data] => {"Reach":400,"Likes":100,"Views":420}
        )

    [1] => Array
        (
            [id] => 3
            [influencer_user_id] => 5
            [content_data] => {"Reach":350}
        )

)
Why i can find the Javascript Array forEach method in Array properties object ?

Why i can find the Javascript Array forEach method in Array properties object ?


By : Federico Segovia
Date : March 29 2020, 07:55 AM
help you fix your problem Array is the constructor. Look at the prototype instead:
Related Posts Related Posts :
  • Login System with a DB Connection Class don't login. Return with else error for invalid login
  • Laravel 4.2 Simple Session Logic not working
  • PHP : get timezone where time is as specified
  • PHP Override an array on file
  • How to upgrade from drush 7 to drush 8 via Composer
  • Dynamic Modal not displaying in table
  • Can I have multiple sessions at the same in PHP?
  • PHP Multiple Filtering Links
  • PHP - XLSX to CSV adding spaces
  • mySQLi SELECT in PHP with another table's IVs for decrypting table column data
  • Insert Text Field Name or ID as Value in MySQL Column
  • How to record the most common time online of a group of users?
  • Switch from mySQL to mariaDB timestamp messup
  • Generating all 6 character alphanumeric combinations (upper and lower case)
  • PHP: Swap placeholders in string variable for corresponding defined variable values
  • HTTP request failed! with file get contents
  • How can I manipulate include_once string?
  • Database table not created after running plugin:refresh
  • Sphinx Get Word in Result through PHP API
  • Sending xml via soapclient in PHP
  • PHP class extension - skipping the middle class by calling the parent of the parent
  • Save data from contentEditable div with mysqli
  • Generating a PDF with sequential order images FPDF
  • How to make a request with PHPLeague oAuth2 client?
  • MySQL count rows with two duplicate column values
  • How to send a curl request with pem certificate via PHP?
  • Request error when processing form in controller
  • Can't save xml file content in mysql with fopen/fwrite/fclose (php)
  • Read only Title from a page?
  • PHP - make echo permanent and visible to all viewers
  • composer fails on server with redmine installed
  • Using foreach With Variables on Smarty
  • How do you specify single print blocks when looping through a 'for' loop?
  • PHP: $_FILES returns empty
  • Symfony2 associative array in entity
  • How do I log every output from a PHP script from the command line?
  • How to implement this json feed into a database structure?
  • Codeigniter, windows, xampp, how to use htaccess to get rid of trailing slash?
  • How to disable Navbar and footer in Yii2 other layouts
  • Json not encode my Special Character
  • echo if POST length is low
  • Warning: require_once error
  • What is this code meaning...?
  • Send to /dev/null a PHP function "echo" output
  • How to store post details and timestamp in database?
  • php mysql - search a row and concatenate values of every columns to variable string
  • Write a program to get N number of positive non-zero integers, so that the sum and product of these numbers are equal
  • Running two multi line queries in PHP
  • PHP/ASP Trouble understanding
  • Strict standards notices View/Layout class
  • how to have backwards reference on PHP's regex?
  • Uncaught exception 'RuntimeException' with message 'Unable to load ZF2. Run `php composer.phar install` or define a ZF2_
  • phpDocumentor: DocBlock with @var tags duplicates descriptions
  • how to push an object to an array within an object with PHP
  • Undefined offset error in for loop
  • mysql query logic for fetching data from 3 related tables on certain condition
  • Saving blob video with php
  • SpeckPaypal ZF2 How to edit the CURRENCY CODE?
  • How to filter associated HABTM data with FriendsOfCake Search for CakePHP 3
  • Check ALL $_POST lengths
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co