Foreach Json Array - php

I have array, where get_# have random number. Need to foreach all items [result][result][get_#RAND_NUM#] and take [id], [name].
Thanks!
Array:
-[result]
--[result]
---[get_1]
----[id] = "1"
----[name] = "dog"
---[get_6]
----[id] = "53"
----[name] = "cat"

According to PHP manual the foreach makes an iteration over array or object. foreach provides $key and $value options. From this $key var you can get the random number you expect.
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.
$data = ['result' => [
'result' => [
'get_1' => ['id' => 1, 'name' => 'doc'],
'get_6' => ['id' => 2, 'name' => 'cat'],
]
]];
$new_data = [];
foreach ($data['result']['result'] as $key => $val) {
// If you want to get the random number uncomment the below line
// $random_no = explode('_', $key)[1]; echo $random_no;
echo "For key {$key}, id = {$val['id']} and name = {$val['name']} </br>";
$new_data[] = ['id' => $val['id'], 'name' => $val['name']];
}
print '<pre>';
print_r($new_data);
Demo

Related

Add multiple MYSQLI results as an array value in a foreach loop

I have this script that converts mysqli records into an array and i'm using a foreach loop to show those results. The problem I have is how can I show the gender value of the array_column as well in the foreach loop too?
I'm only able to show the username value only. I don't know how I can show the gender values in the foreach loop as well. Please don't suggest other loop types. I need to do this with a foreach loop with an array_column.
Here is my code example
<?php
$db_servername='localhost';
$db_username='bbb';
$db_password='1234';
$db_name='test';
$db_connect= new mysqli($db_servername,
$db_username,$db_password,
$db_name);
$db_query= "SELECT*FROM 500_users LIMIT 25";
$db_result= $db_connect->query(
$db_query);
while($db_row= $db_result->fetch_assoc()){
$items[] = $db_row;
}
$array_structure_for_items_value_id = array_column($items,'username','gender');
foreach($array_structure_for_items_value_id as $index => $value){
echo $value.'<br>';//<--username
//echo $value.'<br>';<--I will like to show the gender value as well but how?
}
?>
In the foreach loop you've set up, $index holds the 'user_id'.
echo $index . ': ' . $value
Results in:
"*user_id*: *username*"
If you have an array like this:
$heroes = [
['id' => 10,'hero' => 'superman', 'gender' => 'm'],
['id' => 21,'hero' => 'wonder woman', 'gender' => 'f'],
['id' => 34,'hero' => 'poison ivy', 'gender' => 'f'],
['id' => 46,'hero' => 'penguin', 'gender' => 'm'],
];
And you do this:
$other = array_column($heroes, 'hero', 'id');
You get this:
[
10 => 'superman',
21 => 'wonder woman',
34 => 'poison ivy',
46 => 'penguin'
]
If you iterate through this array, you can only get the index or the hero name because that is all there is in the array.
If you do this:
$other = array_column($heroes, 'hero', 'gender');
You get this:
[
'f' => 'poison ivy',
'm' => 'penguin'
]
Because the gender is used as a key and keys must be unique.
Therefore, it is your use of array_column that is getting in your way.
I don't see why you just don't iterate through your array.
You do not need array_column.
while($db_row= $db_result->fetch_assoc()){
$items[] = $db_row;
}
foreach($items as $item) {
echo $item['hero'].'<br>';
echo $item['gender'] . '<br>';
}
I'm assuming you mean how to show multiple array values in a foreach loop, if that is what you mean then this is my method of your example illustrating that with a third made up array value. Just to give you a better understanding of my example.
<?php
$db_servername='localhost';
$db_username='bbb';
$db_password='1234';
$db_name='test';
$db_connect= new mysqli($db_servername,
$db_username,$db_password,
$db_name);
$db_query= "SELECT*FROM 500_users LIMIT 25";
$db_result= $db_connect->query(
$db_query);
while($db_row= $db_result->fetch_assoc()){
$items[] = $db_row;
}
$array_1 = array_column($items,'username');
$array_2 = array_column($items,'gender');
$array_3 = array_column($items,'password');
$iterator = new MultipleIterator();
$iterator->attachIterator(new ArrayIterator($array_1));
$iterator->attachIterator(new ArrayIterator($array_2));
$iterator->attachIterator(new ArrayIterator($array_3));
foreach($iterator as $index => $value){
echo $index[0].'<br>';
echo $value[0].'<br>';
echo $index[1].'<br>';
echo $value[1].'<br>';
echo $index[2].'<br>';
echo $value[2].'<br>';
}
?>

Creating Associative array (hardcoded key) from foreach in PHP

I have an array called $arr containing some information about users. Using $arr I want to create a new associative array with specific keys. That's what I got so far:
$groups = [];
foreach($arr as $val) {
$groups['first_key_name'] = $val->ID;
$groups['second_key_name'] = $val->login;
}
What I'm trying to achieve is a new array that has the following format:
'first_key_name' => $val->ID
'second_key_name' => $val->login
'first_key_name' => $val->ID
'second_key_name' => $val->login
The problem with my current approach is when I var_dump($groups) I only get one key with an empty value although the array should contain at least 10 entries.
The output of var_dump($groups):
array:1 [▼
"first_key_name" => "4"
]
What am I doing wrong?
You are overwriting your variables each time round the loop in this code
$groups = [];
foreach($arr as $val) {
$groups['first_key_name'] = $val->ID;
$groups['second_key_name'] = $val->login;
}
So instead do
$groups = [];
foreach($arr as $val) {
$groups[] = [
'first_key_name' => $val->ID
'second_key_name' => $val->login
];
}
This will create something like this
[0]
[
'first_key_name' = 1,
'second_key_name' = 99
]
[1]
[
'first_key_name' = 2,
'second_key_name' = 199
]
etc
You approach is overwriting the key value every time. That's why you need to use 2d array.
You can try like this:
$groups = [];
foreach($arr as $val) {
$groups[] = ['first_key_name' => $val->ID, 'second_key_name' => $val->login];
}
What happens here, is you are overwriting first_key_name and second_key_name in each turn of the loop. But you want to get an array with the new key=>value pairs.
To achieve that you have to append a new item to your array called $groups, like this:
$groups = [];
foreach ($arr as $val) {
$groups[] = [
'first_key_name' => $val->ID,
'second_key_name' => $val->login
];
}
You may also use array_map for this:
$groups = array_map(function ($val) {
return [
'first_key_name' => $val->ID,
'second_key_name' => $val->login,
];
}, $arr);

PHP get index into new array

I have a json array like below. I need to get the index into a new array, how is this possible? Arrays are my weakness for some reason just cant grasp them. I can easily get id value, but cannot get the index (e.g 11111111). Any help would be appreciated.
Update please see the revised, my fault for not including the full multi dimensional array.
Below only outputs one result where I need all results.
<?php
$json = '[{
"11111111": {
"id": "val_somevalue5555",
"customer": {
"32312": {
"name": "jane doe"
}
}
},
"2222222": {
"id": "val_somevalue25",
"customer": {
"32312234": {
"name": "jane doe"
}
}
}
}]';
$jsonarr = json_decode($json, true);
$newarr = [];
foreach($jsonarr as $value)
{
$key = key($value);
$newarr[] = ['key' => $key, 'id' => $value[$key]['id']];
}
var_dump($newarr);
expected looped output
key 11111111
id val_somevalue5555
... looped.
You can create an array of the keys of an existing array using the array_keys() function
http://php.net/manual/en/function.array-keys.php
If you don't want the keys in a separate array, and instead just want to access them directly, when you are doing a 'foreach' loop of an array, you can choose to assign a variable to the current key by doing
foreach($jsonarr as $key => $value){...}
Because your original array is actually multidimensional (each $key has a $value that is also stored as an array of "id": "value") - this means taking one more step to get the value of key 'id':
foreach($jsonarr as $key => $value){
$newarray[] = ['key' => $key, 'id' => $value['id'];
}
you can use array_keys() or key() with a foreach loop for this(DEMO):
$newarr = [];
foreach($jsonarr as $value)
{
//$key = array_keys($value)[0];
$key = key($value);
$newarr[] = ['key' => $key, 'id' => $value[$key]['id']];
}
var_dump($newarr);
Output:
array(2) {
[0]=>
array(2) {
["key"]=>
int(11111111)
["id"]=>
string(17) "val_somevalue5555"
}
[1]=>
array(2) {
["key"]=>
int(2222222)
["id"]=>
string(15) "val_somevalue25"
}
}
Edit: With the updated json, you can use the following way, using 2 foreach loops (DEMO):
$newarr = [];
foreach($jsonarr as $json)
{
foreach($json as $key => $value)
{
$newarr[] = ['key' => $key, 'id' => $value['id']];
}
}
PHP supports a slightly different foreach syntax that extracts both the array key and the array value:
foreach ( $jsonarr as $key => $value ) {
$newarr[] = ['key' => $key, 'id' => $value];
}
Use this if you need the key ("11111111" and "2222222" in your example).
<?php
$json = '[{
"11111111": {
"id": "val_somevalue5555"
}
},
{
"2222222": {
"id": "val_somevalue25"
}
}
]';
$jsonarr = json_decode($json, true);
$newarr = [];
foreach($jsonarr as $key => $value) {
$newarr[] = ['key' => key($value), 'id' => current($value)['id']];
}
foreach($newarr as $key) {
echo 'key '.$key['key'] . PHP_EOL;
echo 'id '.$key['id'] . PHP_EOL;
}
If you remove what looks like embedded components in the $json string (otherwise it won't parse) then var_export the output of json_decode() you'll get this:
array (
0 => array (
11111111 => array (
'id' => 'val_somevalue5555',
),
),
1 => array (
2222222 => array (
'id' => 'val_somevalue25',
),
),
)
You have a double-nested array, hence...
foreach ($jsonarr as $obj) {
foreach ($obj as $name=>$value) {
print "$name = $value[id]\n";
break;
}
}
or you can reference the elements directly:
print $jsonarr[0]['11111111']['id'];
First, you are not accessing the deep enough before iterating.
If you call var_export($jsonarr); you will see:
array ( // an indexed array of subarrays
0 =>
array ( // an associative array of subarrays, access via [0] syntax (or a foreach loop that only iterates once)
11111111 => // this is the subarray's key that you want
array (
'id' => 'val_somevalue5555', // this is the value you seek from the id element of 1111111's subarray
'customer' =>
array (
32312 =>
array (
'name' => 'jane doe',
),
),
),
2222222 => // this is the subarray's key that you want
array (
'id' => 'val_somevalue25', // this is the value you seek from the id element of 2222222's subarray
'customer' =>
array (
32312234 =>
array (
'name' => 'jane doe',
),
),
),
),
)
Code: (Demo)
$jsonarr = json_decode($json, true);
$result=[];
// vvvv-avoid a function call (key()) on each iteration by declaring here
foreach($jsonarr[0] as $key=>$subarray){
// ^^^-drill down into the first level (use another foreach loop if there may be more than one)
$result[]=['key'=>$key,'id'=>$subarray['id']];
}
var_export($result);
Output:
array (
0 =>
array (
'key' => 11111111,
'id' => 'val_somevalue5555',
),
1 =>
array (
'key' => 2222222,
'id' => 'val_somevalue25',
),
)
p.s. If $jsonarr has more than one element in its first level, you should use a foreach() loop like this:
foreach($jsonarr as $array1){
foreach($array1 as $key=>$array2){
$result[]=['key'=>$key,'id'=>$array2['id']];
}
}

Transform array to assosiative array in PHP

I want to change my $data format, so that it matches $x's format
$x = [
'021' => [
'province' => 'jatim',
'city' => 'surabaya'
],
'031' => [
'province' => 'jabar',
'city' => 'jakarta'
]
];
$data = [
['031', 'jatim', 'surabaya'],
['021', 'jabar', 'jakarta']
];
Use foreach loops to iterate through your array.
$x = [];
foreach( $data as $d )
{
$x[$d[0]] = ["province"=>$d[1],"city"=>$d[2]];
}
$d[0] represents the initial string ID.
$d[1] represents the province.
$d[2] represents the city.
$result= array();
foreach ($data as $value) {
$result[$value[0]] = array('province'=>$value[1],'city'=>$value[2]);
}
Explanation:
Create resulting array. Fetch through provided array to insert data in resulting array. If needed unset data array if no longer needed.

Access and explode comma-delimited data from multidimensional array then populate a new 2d array

I have a multidimensional array containing comma-separated strings like this
[
[
"users" => [
'email' => 'test#yahoo.com ,testuser#yahoo.com',
'username' => 'test,testuser',
'description' => 'description1,description2'
]
]
]
I want to access the users subarray data, explode on delimiters, and create a new associative array of indexed arrays.
Desired result:
$User = array(
'email' => array(
'test#yahoo.com',
'testuser#yahoo.com'
),
'username' => array(
'test',
'testuser'
),
'description' => array(
'description1',
'description2'
)
);
For only one index:
$arrayTwoD = array();
foreach ($valueMult[0]['User'] as $key => $value) {
$arrayTwoD[$key] = array_push(explode(',', $value));
}
If you have multiple indexes in $multArray:
$arrayTwoD = array();
foreach ($multArray as $keyMult => $valueMult) {
foreach ($valueMult['User'] as $key => $value) {
$arrayTwoD[$keyMult][$key] = array_push(explode(',', $value));
}
}
or
$arrayTwoD = array();
foreach ($multArray as $array) {
foreach ($array['User'] as $key => $value) {
$arrayTwoD[$key] = array_push(explode(',', $value));
}
}
try this
$array = array(...); // your array data
$formedArray = array();
foreach ( $array as $arr )
{
foreach ( $arr['user'] as $key => $value )
{
$formedArray[$key] = array_push(explode(",",$value));
}
}
echo "<pre>";
print_r($formedArray);
echo "</pre>";
It's a little bit repetitive, I know, but you can do like this as well:
foreach($array as $users) {
foreach($users as &$value) { // &value is assigned by reference
$users['users']["email"] = explode(",", $value['email']);
$users['users']["username"] = explode(",", $value['username']);
$users['users']["description"] = explode(",", $value['description']);
}
}
But after that, you need to use $value. Refer to the official PHP manual documentation to know more about what the & symbol does here.
Demo
Using array_map() can be used to access the subset data (without declaring any new variables in the global scope) and make iterate calls of preg_split() to separate the delimited values into subarrays.
Code: (Demo)
var_export(
array_map(
fn($csv) => preg_split('/ ?,/', $csv),
$array[0]['users']
)
);

Categories