Transform array to assosiative array in PHP - 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.

Related

Foreach Json Array

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

create multidimensional json array from a json in php

I have a json data. Now I want to reform it. In my json data there is a property like person_on_zone I want to make a property named person_info and store them which person under this area.
Here is my data any code. Thanks in advance
My json data
$val = [
{
'city':'xx',
'zone':'yy',
'person_on_zone':'p1'
},
{
'city':'xx',
'zone':'yy',
'person_on_zone':'p2'
},
{
'city':'xx',
'zone':'yy',
'person_on_zone':'p3'
},
{
'city':'xx',
'zone':'ww',
'person_on_zone':'p1'
},
]
My expectation is
[
{
'city':'xx',
'zone':'yy',
'person_info':{
'person_on_zone':'p1',
'person_on_zone':'p2',
'person_on_zone':'p3',
}
},
{
'city':'xx',
'zone':'ww',
'person_info':{
'person_on_zone':'p1'
}
},
]
Here I tried
foreach ($val as $v) {
$new_array['city'] = $v['city'];
$new_array['zone'] = $v['zone'];
foreach ($val as $v2) {
$new_array['person_info'] = $v['person_on_zone'];
}
}
json_encode($new_array);
Try this, use $map to store key city-zone, then transform to array to get the result
<?php
$val = [
[
'city' => 'xx',
'zone' => 'yy',
'person_on_zone' => 'p1'
],
[
'city' => 'xx',
'zone' => 'yy',
'person_on_zone' => 'p2'
],
[
'city' => 'xx',
'zone' => 'yy',
'person_on_zone' => 'p3'
],
[
'city' => 'xx',
'zone' => 'ww',
'person_on_zone' => 'p1'
]
];
$map = [];
foreach ($val as $v) {
$key = $v['city'] . $v['zone'];
if (!isset($map[$key])) {
$map[$key] = [
'city' => $v['city'],
'zone' => $v['zone'],
'person_info' => []
];
}
$map[$key]['person_info'][] = $v['person_on_zone'];
}
print_r(array_values($map));
Correct Code
foreach ($val as $v){
$new_array['city'] = $v['city'];
$new_array['zone'] = $v['zone'];
foreach ($val as $v2){
$new_array['person_info'] = $v2['person_on_zone'];
}
}
json_encode($new_array);
try this:
first decode json array then use foreach loop with key
$val = json_decode($val);
foreach ($val as $v){
$new_array['city'] = $v->city;
$new_array['zone'] = $v->zone;
foreach ($val as $key=>$v2){
$new_array[$key]['person_info'] = $v->person_on_zone;
}
}
print_r($new_array);
I think you make a mistake around composing the json. I tried with your code and i found following is the correct way to do.. Remember single quote(') is not valid in json string that is being used to define key value pair in php
// I think your code has json string and i convert it into array of objects(stdClass)
// and if your code has array then keep you code intact but need to change the notation of
// objects to associative array.
// first thing first decode json string
$values = json_decode('[
{ "city":"xx",
"zone":"yy",
"person_on_zone":"p1"
},
{
"city":"xx",
"zone":"yy",
"person_on_zone":"p2"
},
{
"city":"xx",
"zone":"yy",
"person_on_zone":"p3"
},
{
"city":"xx",
"zone":"ww",
"person_on_zone":"p1"
}]');
// Now declare new values as array
$new_values = [];
// walk through each object
foreach ($values as $v){
// $v becomes an object of stdClass here
// $data is a temporary array
$data['city'] = $v->city;
$data['zone'] = $v->zone;
$data['person_info'] = [];
foreach ($values as $v2){
if(!in_array($data['person_info'],['person_on_zone' => $v2->person_on_zone]))
{
// compare if zones are same or not
if($v->zone == $v2->zone)
{
// push to the array instead of assiging
array_push($data['person_info'], ['person_on_zone' => $v2->person_on_zone]);
}
}
}
// make array unique
$data['person_info'] = array_map("unserialize", array_unique(array_map("serialize", $data['person_info'])));
array_push($new_values, $data);
}
// make array unique in mutidimensional array
$new_values = array_map("unserialize", array_unique(array_map("serialize", $new_values)));
echo '<pre>';
print_r($new_values);
echo '</pre>';
One simple foreach would do,
$result = [];
foreach ($arr as $key => $value) {
//created unique combination of city and zone as key
$result[$value['city'] . $value['zone']]['city'] = $value['city'];
$result[$value['city'] . $value['zone']]['zone'] = $value['zone'];
$result[$value['city'] . $value['zone']]['person_info'][] = ['person_on_zone' => $value['person_on_zone']];
}
echo json_encode(array_values($result));die;
array_values — Return all the values of an array
Working demo.

Create an array with indeterminate length starting on 0

I have 50 (or less) arrays from database and I need to return them in one array.
I'm currently using
$results = DB::table('coinflip_history')->where('ct', Auth::user()->steamid)->orWhere('t', Auth::user()->steamid)->orderByRaw('round_id DESC')->limit(50)->get();
$results = json_decode($results, true);
$i=1;
foreach ($results as $key => $value) {
if (!$value['winner']) $array[$i] = array('secret' => null, 'winning_string' => null, 'hash' => $value['hash'], 'timestamp' => $value['time']);
else $array[$i] = array('secret' => $value['secret'], 'winning_string' => $value['percentage'], 'hash' => $value['hash'], 'timestamp' => $value['time']);
$i++;
}
return array($array[1], $array[2], $array[3], $array[4], $array[5], $array[6], $array[7], $array[8], $array[9], $array[10], $array[11], $array[12], $array[13], $array[14], $array[15], $array[16], $array[17], $array[18], $array[19], $array[20], $array[21], $array[22], $array[23], $array[24], $array[25], $array[26], $array[27], $array[28], $array[29], $array[30], $array[31], $array[32], $array[33], $array[34], $array[35], $array[36], $array[37], $array[38], $array[39], $array[40], $array[41], $array[42], $array[43], $array[44], $array[45], $array[46], $array[47], $array[48], $array[49], $array[50]);
But if there are less than 50 arrays it's not working.
Is there any way to make it work automatically?
All arrays have indices.
It's just that kind of data data structure.
There is no way on PHP of generating an array without indices. It wouldn't be an array.
The only thing you are accomplishing with your code is generating an array starting on 1, and then creating a new array starting on 0.
Since both things are functionally equivalent, I guess that the problem exist down the line when you return an 1-based array.
So if you would do:
$array = [];
$results = json_decode($results, true);
foreach($results as $key => $value){
if(!$value['winner']) {
$array[] = [
'secret' => null,
'winning_string' => null,
'hash' => $value['hash'],
'timestamp' => $value['time']
];
}
else {
$array[] = [
'secret' => $value['secret'],
'winning_string' => $value['percentage'],
'hash' => $value['hash'],
'timestamp' => $value['time']
];
}
}
return $array;
You'd get what you need. This is 100% the same than what you are doing up there, but with less steps, and that works for any number of values on the returned $array.
// as simple as this
return $array;

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);

Get certain key and it's value in multidimentional array in php

Suppose I have this array,
$cast = [
'jon' => [
'fullname' => 'Jon Snow',
'class' => 'warrior',
],
'margery' => [
'fullname' => 'Margery Tyell',
'class' => 'politician'
]
];
How do I get the key and it's certain value only? like this,
$name = ['jon'=>'Jon Snow', 'margery'=>'Margery Tyrell'];
Is there any function that support this, so It doesn't have to be loop ?
Any answer will be appreciated!
You can iterate through the multidimensional array, and add the key and the value at index fullname of the inner array in a new one-dimensional array like this:
$names = [];
foreach ($cast as $character => $character_details) {
$names[$character] = $character_details['fullname'];
}
EDIT Alternatively, if you don't want to loop through the elements, you could use array_map function which takes a function as an argument where you can specify how to map each element of the array. In your case, you would simply return the fullname of an element.
$names = array_map(
function ($value) {
return $value['fullname'];
},
$cast
);
I guess that you have iterate over it and extract only interesting you keys. Here you have an example:
function getValuesForKey($array, $key){
$result = [];
foreach($array as $k => $subarray){
if(isset($subarray[$key])){
$result[$k] = $subarray[$key];
}
}
return $result;
}

Categories