logo
down
shadow

Ternary in associative arrays in PHP


Ternary in associative arrays in PHP

By : Pachty
Date : October 21 2020, 08:10 AM
wish helps you How do I do something like this with associative arrays in PHP. , Using ternary operators you could do
code :
$arr =array(
    'title' => 'HelloWorld',
    'access callback' => $user == 'admin' ? 'callbackHello' : 'callbackWorld',
    'access arguments' => $user == 'admin' ? array('arg1', 'arg2') : array('arg3', 'arg4')
);


Share : facebook icon twitter icon
Merge multiple associative arrays to a single array of associative arrays

Merge multiple associative arrays to a single array of associative arrays


By : Namik Kaya
Date : March 29 2020, 07:55 AM
I wish this helpful for you I have 4 associative arrays as per below: , I believe this is your array
code :
$ids = array('0' => '7','1' => '8','2' => '9');
$names = array('0' => 'Name 1','1' => 'Name 2','2' => 'another name');
$marks = array('0' => '8','1' => '5','2' => '8');
$grade = array('0' => '4','1' => '2.5','2' => '4');

#New Keys
$keys = array("id","name","marks","grade");
$final = array();
$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($ids));
$mi->attachIterator(new ArrayIterator($names));
$mi->attachIterator(new ArrayIterator($marks));
$mi->attachIterator(new ArrayIterator($grade));

foreach ( $mi as $value ) {
    $final[] = array_combine($keys, $value);
}
var_dump($final);
$final = array();
foreach ( array_map(null, $ids, $names, $marks, $grade) as $key => $value ) {
    $final[] = array_combine($keys, $value);
}
var_dump($final);
array
  0 => 
    array
      'id' => string '7' (length=1)
      'name' => string 'Name 1' (length=6)
      'marks' => string '8' (length=1)
      'grade' => string '4' (length=1)
  1 => 
    array
      'id' => string '8' (length=1)
      'name' => string 'Name 2' (length=6)
      'marks' => string '5' (length=1)
      'grade' => string '2.5' (length=3)
  2 => 
    array
      'id' => string '9' (length=1)
      'name' => string 'another name' (length=12)
      'marks' => string '8' (length=1)
      'grade' => string '4' (length=1)
Array of associative arrays, add new elements to the associative arrays

Array of associative arrays, add new elements to the associative arrays


By : Dwarakesh Venkat
Date : March 29 2020, 07:55 AM
it fixes the issue If I have an array like this:
code :
foreach($exterior_array as $inside_array) {
    $inside_array['newkey'] = "hihihi";
}
foreach($exterior_array as &$inside_array) {
                           ^- set the reference
    $inside_array['newkey'] = "hihihi";
}
unset($inside_array);
^^^^^^^^^^^^^^^^^^^^^- remove the reference
Converting a non-associative list of arrays to an associative array of arrays

Converting a non-associative list of arrays to an associative array of arrays


By : Epicurus
Date : March 29 2020, 07:55 AM
should help you out A simple loop would do, but that's too boring to post an answer for, so here you go:
code :
$array = array_combine(array_map(function (array $row) { return $row['id']; }, $array),
                       $array);
$array = array_combine(F\pluck($array, 'id'), $array);
Put two different associative arrays inside one associative array as an array with two associative arrays in javascript

Put two different associative arrays inside one associative array as an array with two associative arrays in javascript


By : user1988556
Date : March 29 2020, 07:55 AM
This might help you I Want to join two arrays into one array containing two different arrays First Array. I do not mean a simple array but this time around a more complex array with field having the same values on both sides of the arrays.
code :
const arr1 = [/\*values\*/];

const arr2 = [/\*values\*/];
const $users = arr1.concat(arr2); //[firstValues, secondValues]
const $users = [arr1, arr2]; //[[firstValues], [secondValues]]
How to re-sort an indexed array of associative arrays, based on the values in the associative arrays?

How to re-sort an indexed array of associative arrays, based on the values in the associative arrays?


By : user3053419
Date : March 29 2020, 07:55 AM
will be helpful for those in need If you have Bash 4.3 or newer, you can use namerefs for this, as follows:
code :
sort_by() {
    local arr field sort_params elem
    declare -n arr=$1
    field=$2

    # Build array with sort parameters
    [[ $3 == 'desc' ]] && sort_params+=('-r')
    [[ $field == 'age' ]] && sort_params+=('-n')

    # Schwartzian transform
    for elem in "${arr[@]}"; do
        declare -n ref=$elem
        printf '%s\t%s\n' "${ref["$field"]}" "$elem"
    done | sort "${sort_params[@]}" | cut -f2
}

declare -A assoc1=([name]=aaa [age]=20)
declare -A assoc2=([name]=bbb [age]=40)
declare -A assoc3=([name]=ccc [age]=25)
indexed_array=(assoc1 assoc2 assoc3)

readarray -t byage < <(sort_by indexed_array age desc)
declare -p byage

readarray -t byname < <(sort_by indexed_array name asc)
declare -p byname
sort_by ARRAYNAME FIELD SORTORDER
declare -n arr=$1
declare -n ref=$elem
20      assoc1
40      assoc2
25      assoc3
declare -a byage=([0]="assoc2" [1]="assoc3" [2]="assoc1")
declare -a byname=([0]="assoc1" [1]="assoc2" [2]="assoc3")
Related Posts Related Posts :
  • Running two PHP versions on the same server (STRETCH)
  • Checking if a file has been selected for upload
  • Model not updating laravel
  • How to add a description of words from text to an array, to an array key by passing words?
  • Nginx rewrite rule not not passing variables if "/" is at the end of the url
  • Modify decimal point and thousands separator without changing the number of decimals
  • Remove PHP errors from CLI and PHPMyAdmin
  • Yii2 rest api - Url manager add parameters
  • 1-query batch update array of users using PDO
  • Keep getting error: implode(): Invalid arguments passed when updating data
  • Laravel 5.4 - Correct Validation rule for a required parameter that can be zero
  • What does this code mean: $objPHPExcel->getActiveSheet()->toArray(null, true,true,true)
  • Data not being added to mysql table but echo's the data?
  • While fetch row in PHP
  • IP long string filter
  • How to view first image in list per user as its highlight Profile
  • Insert multiple rows from array
  • PHP : How to remove a duplicate array item ONCE
  • Print the input box text as simple text instead of html tag
  • How to read a string variable in php as $_GET or $_POST?
  • MySQL query fetch array not working
  • LogicException with message '... must return a relationship instance.'
  • PHP - create new array with only selected keys from an existing array
  • How to allow backgrounding a process to survive a session termination?
  • How to redirect to Home page (Default page) in zend framework 2?
  • I want to call a jquery variable in php syntax
  • Disabling the default /?add-to-cart= animation on buttons in Woocommerce
  • How to use query data for another sql query in yii2
  • Replace string enclosed in specified characters based on data type
  • Symfony FormType: how to get prototype in form type file
  • Handle reply messages properly after some operations in php
  • PHP Changed Domain, how to remove old Session Cookies
  • mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in php
  • Error: Call to a member function update() on array laravel
  • How to change the format of a float number?
  • run ajax requests by order
  • Wordpress Install 404 Error (Cannot view login in browser)
  • Calcinai xero-php pass config once
  • Fatal error calling to undefined function in PHP file
  • Laravel hasMany and belongsTo parameters
  • How do I call a Controller method in php Laravel?
  • How to replace "@" post tag with regex in PHP?
  • Laravel : when insert record in table. How can i add that Record in the list without querying the db
  • It is possible that I could user email address to get customer id from simPRO API?
  • PHP add and merge sql result
  • laravel ckeditor dark theme
  • Laravel belongsToMany not working
  • laravel 5.4 datatables not working jquery $ referenceError
  • Zend Form 2 multiselect field is empty after validation
  • PHP - Laravel 5 get data to html table from 3 SQL database tables with column DATA as headers
  • Can't use token authorization with Laravel Passport
  • splitting lines of dates and presenting in desired format
  • Laravel 5.2 Heroku Deployment Failed to install system packages
  • Laravel relationships - are there multiple *unnecessary* database calls?
  • htaccess rewrite rule for serving index.php from parent directory
  • PHP/MongoDB - $concat aggregation
  • Remove ajax.googleapis.com from my Wordpress site
  • Image saved always empty with Storage::put in Laravel
  • How to count and sort data in junction table
  • Get common number of values in a single array
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org